Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if file exists on remote host with ssh

I would like to check if a certain file exists on the remote host. I tried this:

$ if [ ssh user@localhost -p 19999 -e /home/user/Dropbox/path/Research_and_Development/Puffer_and_Traps/Repeaters_Network/UBC_LOGS/log1349544129.tar.bz2 ] then echo "okidoke"; else "not okay!" fi -sh: syntax error: unexpected "else" (expecting "then")  
like image 307
stdcerr Avatar asked Oct 11 '12 17:10

stdcerr


2 Answers

In addition to the answers above, there's the shorthand way to do it:

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist"; 

-q is quiet mode, it will suppress warnings and messages.

As @Mat mentioned, one advantage of testing like this is that you can easily swap out the -f for any test operator you like: -nt, -d, -s etc...

Test Operators: http://tldp.org/LDP/abs/html/fto.html

like image 117
JP Lew Avatar answered Oct 08 '22 14:10

JP Lew


Here is a simple approach:

#!/bin/bash USE_IP='-o StrictHostKeyChecking=no [email protected]'  FILE_NAME=/home/user/file.txt  SSH_PASS='sshpass -p password-for-remote-machine'  if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1             then                     echo "File exists"             else                     echo "File does not exist"  fi 

You need to install sshpass on your machine to work it.

like image 35
Florin Stingaciu Avatar answered Oct 08 '22 12:10

Florin Stingaciu