How to check if any errors occurred during ssh?
The exit status of ssh
will be the exit status of the remote command. For instance
ssh myapp 'exit 42'
echo $?
should print 42 ($?
is the exit status of the last command executed).
One option is to exit right away if the mkdir
fails:
ssh myapp 'mkdir /some/dir || exit 42; do-more-stuff'
if [[ $? = 1 ]]; then
echo "Remote mkdir failed"
fi
It is probably better to try to handle any remote failures in your script, if possible.
If you really need to catch the error message you can try this:
#!/bin/bash
result=`ssh myapp 'mkdir /some/dir' 2>&1`
if [[ -n $result ]]; then
echo "the following error occurred: $result"
fi
By this you redirect the standard error output to the standard output and save the output of the ssh command to $result
. If you just need the error code / exit status, see this answer.