1

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
Logan
  • 1,682
  • 4
  • 21
  • 35

2 Answers2

1

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
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
0

sshpass is scarcely used.

Maybe the same as with sshuse batch mode works

sshpass -p PASSWORD ssh -o BatchMode=yes root@192.168.16.01 "if [ -d /home/test ] ; then echo Y ; fi" > a.out

You will then collect the result in a.out

J. Chomel
  • 8,193
  • 15
  • 41
  • 69