0

My script contains a ssh command to login to remote server and execute a few commands, The command checks if a file exist and if not it should come out of the entire script.

ssh $user@$hostname "if[ -f $filename];then 
  echo"file exists Proceeding next steps;
else 
  "echo file doesn't exist";
   exit 1;
fi"

However the above command gets executed successfully if the file present But in other case if file doesn't exist, the exit command just comes out of the ssh session

It still continues with other commands in the script rather exiting script.

Please help me with your suggestions.

2

To execute a script with ssh, which needs certain variables that are set previously, e.g. your $filename, do the following:

ssh user@host 'bash -s' < local_script.sh "$filename"

Contents of local_script.sh:

#!/bin/bash
[ $# -ne 1 ] && echo '$0 needs at least 1 parameter' 1>&2 && exit 2
filename="$1"

if [ ! -f "$filename" ]; then
  echo "[ $filename ] does not exist"
  exit 1
fi
echo "[ $filename ] exists"

If you don't need any passed variables in your to be executed command, this works:

ssh user@host '
  if [ ! -f "test/stuff" ]; then
    echo "File does not exist"
    exit 1
  fi
  echo "File exists"
'

Mind the single quotes ', they prevent your command from being expanded.

Also I checked for the non-existence of $filename first to reduce lines of code and used tabs/whitespaces.

To make your command more readable, try this

ssh user@host <<'ENDSSH'
  if [ ! -f "test/stuff" ]; then
    echo "File does not exist"
    exit 1
  fi
  echo "File exists"
ENDSSH

Source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.