0

I'm looking for the best way to fill in multiple arrays from command's output using Bash.

The solution I figured out at this stage is:

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

The output is:

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

Thanks in advance.

Arsene

1 Answer 1

3

An immediate improvement that you can do is to not read the line as a whole:

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

However, you will likely suddenly have it stop working once you want to use the arrays for more than just printing inside the loop. Since you're setting them in a subshell, the parent will not be affected. Here's one of the possible fixes:

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.