LoganPHP LoganPHP - 2 years ago 199
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@ /home/test" ]; then
echo "YES"

Way 2 :

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

Answer Source

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>

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@ '[ -d /home/test ]'; then
    echo "YES"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download