0

I am trying to create a script (test.sh) that logs on to another server and checks the disk usage of some different folders:

test.sh:

DIRS="dir_A dir_B dir_C"

for DIR in $DIRS
do
  sshpass -p user_password ssh -o StrictHostKeyChecking=no user_name@host 'cd /opt/app/$DIR;SIZE=$(du -s);echo "YVALUE="$SIZE > ../size_$DIR.txt'
done

However, the variable DIR never gets passed to the script. It is empty when I run the script. I have tried using {} around $DIR but still no success. What am I missing? Thanks for your help!

2 Answers 2

2

Basically, use double-quotes instead of single-quotes. You can still concatenate with single quotes if necessary:

sshpass -p user_password ssh -o StrictHostKeyChecking=no user_name@host 'cd /opt/app/'"$DIR"';SIZE=$(du -s);echo "YVALUE="$SIZE > ../size_'"$DIR".txt

I just noticed something: du -s produces an output of two columns so probably it's not being used the proper way yet. Perhaps something like SIZE=${SIZE%$'\t'*} is still needed.

Another way is to send the directory by input and let the other end read it:

sshpass -p user_password ssh -o StrictHostKeyChecking=no user_name@host 'read -r DIR; cd "/opt/app/$DIR"; SIZE=$(du -s); echo "YVALUE=$SIZE" > "../size_$DIR.txt"' <<< "$DIR"

This would be helpful if directories contain spaces or characters that may cause syntax errors. Using an array is also recommended for it:

DIRS=('DIR 1' 'DIR 2' 'DIR 3')
for DIR in "${DIRS[@]}"; do
    sshpass ...
done
Sign up to request clarification or add additional context in comments.

Comments

1

Wrapping a string in single quotes (') will stop any bash expansion taking place, you will need to use double quotes for $DIR to be evaluated, escaping any double quotes within the string that you want to send over SSH:

  sshpass -p user_password ssh -o StrictHostKeyChecking=no user_name@host "cd /opt/app/$DIR;SIZE=\$(du -s);echo \"YVALUE\"=$SIZE > ../size_$DIR.txt"

1 Comment

I would assume that the dollar in $(du -s) should also be escaped, otherwise he will be getting the local path size. Konsolebox's answer is better in my opinion anyway though, as it is less error prone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.