How to check if a file exists on a remote server using the shell

I searched many times and I can’t figure out how to do this using a shell script. Basically, I copy files from remote servers, and I want to do something else if it does not exist. I have an array below, but I tried to reference it directly, but it still returns false.

I am new to this, so please be kind :)

declare -a array1=(' user1@user1.user.com '); for i in "${array1[@]}" do if [ -f "$i:/home/user/directory/file" ]; then do stuff else Do other stuff fi done 
+5
source share
2 answers

Assuming you are using scp and ssh for remote connections, something like this should do what you want.

 declare -a array1=(' user1@user1.user.com '); for i in "${array1[@]}"; do if ssh -q "$i" "test -f /home/user/directory/file"; then scp "$i:/home/user/directory/file" /local/path else echo 'Could not access remote file.' fi done 

Alternatively, if you don’t have to care about the difference between a deleted file that does not exist and other possible scp errors, then the following will work.

 declare -a array1=(' user1@user1.user.com '); for i in "${array1[@]}"; do if ! scp "$i:/home/user/directory/file" /local/path; then echo 'Remote file did not exist.' fi done 
+2
source

Try the following:

 ssh -q $HOST [[ -f $i:/home/user/directory/file ]] && echo "File exists" || echo "File does not exist"; 

or like this:

 if ssh $HOST stat $FILE_PATH \> /dev/null 2\>\&1 then echo "File exists" else echo "File not exist" fi 
+4
source

All Articles