You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
you can use man or info to find the meaning of an exit status
ex:
man ping
ex: grep will return 1 if no search pattern is found
$? contains the return code of the previously executed command
ls /not/here/
echo "$?"
# it will output 2
example of using an error code:
#!/bin/bash
HOST="google.com"
ping -c 1 $HOST
if [ "$?" -eq "0" ]
then
echo "$HOST reachable."
else
echo "$HOST unreachable."
fi
another example - only checking for an error:
#!/bin/bash
HOST="google.com"
ping -c 1 $HOST
if [ "$?" -ne "0" ]
then
echo "$HOST unreachable."
fi
another example - assign the return code to a variable:
#!/bin/bash
HOST="google.com"
ping -c 1 $HOST
RETURN_CODE=$?
if [ "$RETURN_CODE" -ne "0" ]
then
echo "$HOST unreachable."
fi
Using && or || with exit statuses
you can also use && or || with return codes
&& = and
# both will run
# the second command will only run if the first command succeeds
mkdir /tmp/bak && cp test.txt /tmp/bak
|| = or
# if the first command suceeds then the second command will not run
# if the first command fails then the second command will be run
cp test.txt /tmp/bak/ || cp test.txt /tmp