Search code examples
bashunixsshexit-code

exit code from ssh command


I'm trying to retrieve the code return from this script:

#!/bin/bash
echo "CM  1"
ssh -i key/keyId.ppk user@X.X.X.X "
grep blabla ddd
if [ ! $? -eq 0 ]; then exit 1; fi
"
echo $?

But the last command echo $? returns 0 instead of 1.

And if try to run separately (not as a script) :

  • the ssh command: ssh -i key/keyId.ppk user@X.X.X.X
  • grep blabla ddd => I get the msg "grep: ddd: No such file or directory"
  • then: if [ ! $? -eq 0 ]; then exit 1; fi
  • then: echo $? => it returns 1 as expected

Do you have an idea why it doesn't work in my script ?

Thank you


Solution

  • This code

    ssh -i key/keyId.ppk user@X.X.X.X "
    grep blabla ddd
    if [ ! $? -eq 0 ]; then exit 1; fi
    "
    

    evaluates $? in your shell and not in the remote one, because the $ is not escaped in single quotes. You should escape that to reach desired behaviour. Once to avoid evaluation in your local shell, for the second time to avoid evaluation when it is passed to the bash on remote side. Or rather put the command into single quotes:

    ssh -i key/keyId.ppk user@X.X.X.X '
    grep blabla ddd
    if [ ! $? -eq 0 ]; then exit 1; fi
    '