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
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).
echo $?
$?
echo