LoganPHP LoganPHP - 7 months ago 71
Bash Question

how to use sshpass in shell script to check whether directory exists or not?

I have a shell script, it basically run in one environment, and it needs to check whether directory exists on another environment or not.

I tried in below two ways but no luck.

Way 1 :

if [ -d "sshpass -p PASSWORD ssh root@192.168.16.01 /home/test" ]; then
echo "YES"
fi


Way 2 :

if [sshpass -p PASSWORD ssh root@192.168.16.01 '[ -d /home/test ]']; then
echo "YES"
fi

Answer

The square brackets in if tests are not part of the if syntax. The [ is a command of its own (also called test).

The syntax of an if statement is roughly (see Shell Grammar Rules for more if you are really curious):

if <command that returns true or false>; then
    <other commands>
fi

Your first attempt is just incorrect because -d takes a directory name not a string which is a command you want to run.

The second attempt is close you just have too many square brackets (and not enough spaces for those square brackets).

Remove the outer square brackets from the second attempt and it will work (assuming sshpass properly handles returning the return value of the ssh command):

if sshpass -p PASSWORD ssh root@192.168.16.01 '[ -d /home/test ]'; then
    echo "YES"
fi
Comments