Bash script to check if file exists on a remote server

Here is an example of a check if a file exists on the remote server and takes action locally, inside a shell script.

if [ $(ssh codetryout [[ -f /etc/passwd ]];echo $?) -eq 0 ]; then
    echo "Remote file exists"
fi

Script explanation, line by line:

From the code snippet, the remote file-check expression is:

ssh codetryout [[ -f /etc/passwd ]]

This command will ssh to the remote host (server) “codetryout” and test if the file “/etc/passwd” exists.

Based on the expression in the block [[ ….]] the status code will be passed as a number:

echo $?

This will echo the return status of the ssh command file check, for example –

  • Return 0 if it was a success – the file exists on the remote server.
  • Return 1 if the test was returned false – the file does not exist.

To learn more about bash return codes (error codes) please check this page: codetryout.com/bash-last-command-return-code/

bash check if the file exists on a remote server