Home > Enterprise >  Arrays in Bash and running stat against each directory
Arrays in Bash and running stat against each directory

Time:07-19

I have an unknown set of files/folders (I keep having to add to the list) that I need to check for owner and permissions. So I pieced together

dirs=(/mnt /mnt/data /mnt/data/1.txt)
for i in $(dirs[@]}; do
stat -c "%U:$G" ${dirs[$i]}
done

However, I receive a syntax error 'operand expected (error token is "/mnt"'

point me in the right direction please

CodePudding user response:

for i in ${dirs[@]} isn't iterating the indices of the array, but the actual contents.

Try this:

dirs=(/mnt /mnt/data /mnt/data/1.txt)
for i in "${dirs[@]}"; do
stat -c "%U:$G" "$i"
done

EDIT With cleaner variable names per glennjackman's suggestion:

paths=(/mnt /mnt/data /mnt/data/1.txt)
for path in "${paths[@]}"; do
stat -c "%U:$G" "$path"
done

CodePudding user response:

To follow up on @tjm3772's answer: if you want to iterate over the array's indices:

for idx in "${!dirs[@]}"
# ............^
do
  stat -c "%U:$G" "${dirs[i]}"
done

See 6.7 Arrays in the manual

  • Related