Huckleberry Finn Huckleberry Finn - 3 months ago 8
Linux Question

Bash Looping 2 Arrays with whitespaces in variables

I'm working on a script to find the disk usage of directories on a server.
I need to handle folders with spaces in the name.

I'm having trouble using a for loop to run through each variable with spaces, as it will see them as two separate vars.

Current Snippet:



scandest="/root/*"
usedest="/root/fileusage/diskusage"

diskusage=$(du -sh $scandest > $usedest)

dir=($(cat $usedest|cut -f2|cut -c7-))
storage=($(cat $usedest|cut -f1))

echo "${dir[@]}"


This will output the following:

anaconda-ks.cfg
file test
fileusage
install.log
install.log.syslog


The file "file test" will get split once run through my loop.

So If I can echo this with quotes around each variable - then I'll be able to continue. Or if someone has a better idea for what I'm trying to achieve, I'm all ears!

Thank you

Edit 2



Loop is containing 2 arrays dir and storage

for ((i=0;i<${#dir[@]};i++)); do
echo "${dir[$i]}" -- "${storage[$i]}"
done


Which in turn outputs:

anaconda-ks.cfg -- 4.0K
file -- 0
test -- 16K
fileusage -- 12K
install.log -- 4.0K
install.log.syslog --


As you can see "file test" is treated as two variables.

Answer

I suggest using du -0 option to null terminate output from du and use this while loop to iterate:

while read -d '' -r size name; do
    printf "%s -> %s\n" "$size" "$name"
done < <(du -sh -0 /root/*)

This will avoid creation of temporary file and use of multiple error prone cut commands.

Comments