In a loop in shell script, I am connecting to various servers and running some commands. For example
#!/bin/bash FILENAME=$1 cat $FILENAME | while read HOST do 0</dev/null ssh $HOST 'echo password| sudo -S echo $HOST echo $? pwd echo $?' done
Here I am running "echo $HOST" and "pwd" commands and I am getting exit status via "echo $?".
My question is that I want to be able to store the exit status of the commands I run remotely in some variable and then ( based on if the command was success or not) , write a log to a local file.
Any help and code is appreciated.
You can simply do a echo $? after executing the command/bash which will output the exit code of the program. Every command returns an exit status (sometimes referred to as a return status or exit code).
To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.
Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .
ssh
will exit with the exit code of the remote command. For example:
$ ssh localhost exit 10 $ echo $? 10
So after your ssh
command exits, you can simply check $?
. You need to make sure that you don't mask your return value. For example, your ssh command finishes up with:
echo $?
This will always return 0. What you probably want is something more like this:
while read HOST; do echo $HOST if ssh $HOST 'somecommand' < /dev/null; then echo SUCCESS else echo FAIL done
You could also write it like this:
while read HOST; do echo $HOST if ssh $HOST 'somecommand' < /dev/null if [ $? -eq 0 ]; then echo SUCCESS else echo FAIL done
You can assign the exit status to a variable as simple as doing:
variable=$?
Right after the command you are trying to inspect. Do not echo $?
before or the new value of $?
will be the exit code of echo
(usually 0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With