Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script ssh command exit status

Tags:

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.

like image 894
Kashif Usmani Avatar asked Mar 13 '13 16:03

Kashif Usmani


People also ask

How do I get exit status in shell?

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).

How do you exit a command shell script?

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.

What is exit 10 in shell script?

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 .


2 Answers

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 
like image 168
larsks Avatar answered Oct 19 '22 13:10

larsks


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).

like image 41
Eduardo Bissi Avatar answered Oct 19 '22 15:10

Eduardo Bissi