如何从ls -l拆分输出以正确格式显示

问题描述

我正在编写一个bash脚本,用于格式化ls-l的输出,使其看起来像这样

Owner Group Other Filename
----- ----- ----- --------
rwx   rwx    rwx   myDIR1
rwx   r-x    --x   myDIR2
Links: 4 Owner: unx510 Group: users Size: 229 Modified: Feb 22 2015

我的脚本称为pathdisplay,并将目录路径作为参数传递给它。例如

=>bash ./pathdisplay /home

我不知道如何分割ls ​​-l命令的输出。这是我到目前为止所拥有的:

echo "Owner   Group   Other   Filename"
echo "-----   -----   -----   --------"
                                                                                                                                                                                                                               
ls -l $1 | grep '^d' | tr -s ' ' | cut -d' ' -f1,9 |  
while read line                                                                                                         
do
userPermissions=$(cut -b 2-4)
groupPermissions=$(cut -b 5-7)
otherPermissions=$(cut -b 8-10)
dirName=$(cut -b 11-)
echo -n "$userPermissions   $groupPermission   $otherPermission  $dirName"
stat -c "links:%h,owner:%U,group:%G,size:%B,modified:%y" "$dirName"
done  

这就是我要得到的


Owner   Group   Other   Filename
-----   -----   -----   --------
rwx        stat: missing operand

解决方法

处理文件名的最安全方法是

for line in "$@"
  do
    test -e "$line" || continue
    stat "$line"
done

不确定是要显示父目录还是子目录,但是可以像这样遍历子目录(跟踪/仅与目录匹配)

echo Owner$'\t'Group$'\t'Other$'\t'Filename
echo -----$'\t'-----$'\t'-----$'\t'--------

for line in "$@"
  do
    test -e "$line" || continue
    for file in "$line"/*/ "$line"/.*/
      do
        file="${file%/}"
        [ -e "$file" ] && [ "${file##*/}" != "." ] && [ "${file##*/}" != ".." ] || continue
        perm=$(stat -c%A "$file")
        user=${perm:1:3}
        group=${perm:4:3}
        other=${perm:7:3}

        size=$(du -Lhd0 "$file" | cut -f1)
        printf -v mtime '%(%b %d %Y)T' $(stat -c%Y "$file")

        printf '%s\t%s\t%s\t%s\n' $user $group $other "${file##*/}"
        stat -c "links: %h,owner: %U,group: %G,size: $size,modified: $mtime" "$file" 

    done
done