从命令的输出中填写多个数组--Bash

时间:2013-03-16 22:35:47

标签: arrays bash file command output

我正在寻找使用Bash从命令输出中填充多个数组的最佳方法。

我在这个阶段想出的解决方案是:

i=1
ls -al | while read line
do
            # Separate columns into arrays
            array_filetype[ $i ]=`echo $line | awk '{print $1}'`
            array_owner[ $i ]=`echo $line | awk '{print $3}'`
            array_group[ $i ]=`echo $line | awk '{print $4}'`
            echo "${array_filetype[$i]} - ${array_owner[$i]} - ${array_group[$i]}"
    (( i++ ))
done

输出结果为:

drwxrwxr-x - arsene - arsene
drwx--x--- - arsene - arsene
-rw-rw-r-- - arsene - arsene
-rw-rw-r-- - arsene - arsene
-rw-rw-r-- - arsene - arsene
-rw-rw-r-- - arsene - arsene
-rw-rw-r-- - arsene - arsene
-rwx------ - arsene - arsene
-rwx------ - arsene - arsene
-rwxr-xr-x - arsene - arsene
-rwx------ - root - root

提前致谢。

阿瑟

1 个答案:

答案 0 :(得分:3)

你可以立即做的改进就是不要整体读取这条线:

i=1
ls -al | while read type links owner group rest-of-line-we-dont-care-about
do
     # Separate columns into arrays
     array_filetype[$i]=$type
     array_owner[$i]=$owner
     array_group[$i]=$group
     echo "${array_filetype[$i]} - ${array_owner[$i]} - ${array_group[$i]}"
    (( i++ ))
done

但是,一旦您想要使用数组不仅仅是在循环内打印,您可能会突然停止工作。由于您在子shell中设置它们,因此父级不会受到影响。这是可能的修复之一:

i=1
while read type links owner group rest-of-line-we-dont-care-about
do
     # Separate columns into arrays
     array_filetype[$i]=$type
     array_owner[$i]=$owner
     array_group[$i]=$group
     echo "${array_filetype[$i]} - ${array_owner[$i]} - ${array_group[$i]}"
    (( i++ ))
done < <(ls -al)