exit statement will not break while loop in unix shell - shell

The exit statements in each status check if statement do not break the while loop and truly exit the script. Is there something I can do to break the loop and exit with that $STATUS code?
EDIT: I've updated my code and it still isn't working. The status check if statements successfully break the loop but when I try to evaluate the $EXIT_STATUS it's always null, likely having something to do with scope. What am I missing here?
if [ $RESTART -le $STEP ]; then
. tell_step
while read XML_INPUT; do
XML_GDG=`get_full_name $GDG_NAME P`
cp $XML_INPUT $XML_GDG
STATUS=$?
EXIT_STATUS=$STATUS
if [ $STATUS -ne 0 ]; then
break
fi
add_one_gen $XML_GDG
STATUS=$?
EXIT_STATUS=$STATUS
if [ $STATUS -ne 0 ]; then
break
fi
done < $XML_STAGE_LIST
echo $EXIT_STATUS
if [ $EXIT_STATUS -ne 0 ]; then
exit $EXIT_STATUS
fi
fi

I had the same problem: when piping into a while loop, the script did not exit on exit. Instead it worked like "break" should do.
I have found 2 solutions:
a) After your while loop check the return code of the while loop and exit then:
somecommand | while something; do
...
done
# pass the exit code from the while loop
if [ $? != 0 ]
then
# this really exits
exit $?
fi
b) Set the bash script to exit on any error. Paste this at the beginning of your script:
set -e

Not really understand why your script dosn't exits on exit, because the next is works without problems:
while read name; do
echo "checking: $name"
grep $name /etc/passwd >/dev/null 2>&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "grep failed for $name rc-$STATUS"
exit $STATUS
fi
done <<EOF
root
bullshit
daemon
EOF
running it, produces:
$ bash testscript.sh ; echo "exited with: $?"
grep failed for bullshit rc-1
exited with: 1
as you can see, the script exited immediatelly and doesn't check the "daemon".
Anyway, maybe it is more readable, when you will use bash functions like:
dostep1() {
grep "$1:" /etc/passwd >/dev/null 2>&1
return $?
}
dostep2() {
grep "$1:" /some/nonexistent/file >/dev/null 2>&1
return $?
}
err() {
retval=$1; shift;
echo "$#" >&2 ; return $retval
}
while read name
do
echo =checking $name=
dostep1 $name || err $? "Step 1 failed" || exit $?
dostep2 $name || err $? "Step 2 failed" || exit $?
done
when run like:
echo 'root
> bullshit' | bash testexit.sh; echo "status: $?"
=checking root=
Step 2 failed
status: 2
so, step1 was OK and exited on the step2 (nonexisten file) - grep exit status 2, and when
echo 'bullshit
bin' | bash testexit.sh; echo "status: $?"
=checking bullshit=
Step 1 failed
status: 1
exited immediatelly on step1 (bullshit isn't in /etc/passwd) - grep exit status 1

You'll need to break out of your loop and then exit from your script. You can use a variable which is set on error to test if you need to exit with an error condition.

I had a similar problem when pipelining. My guess is a separate shell is started when piplining. Hopefully it helps someone else who stumbles across the problem.
From jm666's post above, this will not print 'Here I am!':
while read name; do
echo "checking: $name"
grep $name /etc/passwd >/dev/null 2>&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "grep failed for $name rc-$STATUS"
exit $STATUS
fi
done <<EOF
root
yayablah
daemon
EOF
echo "Here I am!"
However the following, which pipes the names to the while loop, does. It will also exit with a code of 0. Setting the variable and breaking doesn't seem to work either (which makes sense if it is another shell). Another method needs to be used to either communicate the error or avoid the situation in the first place.
cat <<EOF |
root
yayablah
daemon
EOF
while read name; do
echo "checking: $name"
grep $name /etc/passwd >/dev/null 2>&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
echo "grep failed for $name rc-$STATUS"
exit $STATUS
fi
done
echo "Here I am!"

Related

Is "exit ${?}" correct to use in bash?

Let's say I code something like:
if [ ${?} -ne 0 ]; then
exit ${?}
Would this work properly?
Is this correct "syntax-wise"?
The [ command in your if statement will set $? after it checks. You'll need to save the original exit status before testing.
some_command
es=$?
if [ "$es" -ne 0 ]; then
exit "$es"
fi
The syntax is correct, but $? is reset by the [ ... ] command in the if statement. By definition, if the if block is entered then the [ ... ] test must have been successful, and $? is guaranteed to be 0.
You'll need to save it in a variable.
result=$?
if ((result != 0)); then
exit "$result"
fi
Alternately, it's more idiomatic to test the result of a command directly rather than testing $?. If you do so then you don't have the problem of $? changing.
if command; then
echo success
else
exit # `exit` is equivalent to `exit $?`
fi
If you don't care about success then you can use ||:
command || exit
If you want to exit on error and preserve the EXIT code of the command, you can enable the errexit option:
Either with: set -e
Either with: set -o errexit
See: help set | grep -F -- -e
-e Exit immediately if a command exits with a non-zero status.
errexit same as -e
Alternatively you can trap the ERR signal and use this to exit with the return code of the error.
This will save you from dealing with the -e option consequences.
#!/usr/bin/env bash
err_handler() {
set -- $?
printf 'The error handler caught code #%d\n' "$1" >&2
exit "$1"
}
trap 'err_handler' ERR
create_error() {
[ $# -ne 1 ] && return 0
printf 'Create error #%d\n' "$1"
return "$1"
}
create_error "$#"
Testing with different errors:
for e in 1 0 2; do ./a.sh "$e" ;echo $?; done
Create error #1
The error handler caught code #1
1
Create error #0
0
Create error #2
The error handler caught code #2
2

Last command exit code comparison in .bashrc

As all of you probably know, bash can print the last command exit code. This works for me, but I wanted to improve it by adding an if statement which checks if $? was 0. If it is 0 print the code in white, and if it is different, print it in red. Unfortunately this does not seem to work:
if [ $? == "0" ]; then
PS1=${PS1}'$(echo ${?})'
else
PS1=${PS1}'\e[1;31m\]$(echo ${?})'
fi
I also tried:
if [ $(echo $?) == "0" ]; then
PS1=${PS1}'$(echo ${?})'
else
PS1=${PS1}'\e[1;31m\]$(echo ${?})'
fi
also:
if [ $(echo ${?}) == "0" ]; then
PS1=${PS1}'$(echo ${?})'
else
PS1=${PS1}'\e[1;31m\]$(echo ${?})'
fi
None of them working.
Somehow variable is always 0, therefore printed in white.
How is it possible that I can print exit code, but cannot examine it with "if" ? Is this a bash limitation, or I am doing something wrong?
Just add $? to the PS1.
> PS1='PS $ '
> PS $ echo 1
> 1
> PS $ PS1='PS $? $ '
> PS 0 $ false
> PS 1 $ true
> PS 0 $
If you want to change color, you would have to do it inside PS1, not statically... Also note that $? will change it's value, so you need to save it.
PS1=${PS1}'$(ret=$?; if [ "$ret" -ne 0 ]; then printf "\e[1;31m\]"; fi; printf "%d" "$ret")'
$? is the exit status of the last command. If you execute some command, for instance [ … = … ], then $? changes. Example:
myCmd
echo $? # prints exit status of myCmd
echo $? # prints exit status of echo
myCmd
if [ $? = 0 ]; then
echo $? # prints exit status of `[`, here 0
else
echo $? # prints exit status of `[`, here 1
fi
Store the exit status of myCmd in a separate variable if you want to access it later.
myCmd
exitStatus=$?
echo $exitStatus # prints exit status of myCmd
echo $exitStatus # prints exit status of myCmd
By the way: "$(echo ${?})" is overly complicated; just "$?" is better in every way.

Only run code if git tag exists for current commit in BASH [duplicate]

What would be the best way to check the exit status in an if statement in order to echo a specific output?
I'm thinking of it being:
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code. Also, I know I'm doing something wrong since the exit would obviously exit the program.
Every command that runs has an exit status.
That check is looking at the exit status of the command that finished most recently before that line runs.
If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.
That being said, if you are running the command and are wanting to test its output, using the following is often more straightforward.
if some_command; then
echo command returned true
else
echo command returned some error
fi
Or to turn that around use ! for negation
if ! some_command; then
echo command returned some error
else
echo command returned true
fi
Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.
Note that exit codes != 0 are used to report errors. So, it's better to do:
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
instead of
# will fail for error codes == 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
An alternative to an explicit if statement
Minimally:
test $? -eq 0 || echo "something bad happened"
Complete:
EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
$? is a parameter like any other. You can save its value to use before ultimately calling exit.
exit_status=$?
if [ $exit_status -eq 1 ]; then
echo "blah blah blah"
fi
exit $exit_status
For the record, if the script is run with set -e (or #!/bin/bash -e) and you therefore cannot check $? directly (since the script would terminate on any return code other than zero), but want to handle a specific code, #gboffis comment is great:
/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
...
Just to add to the helpful and detailed answer:
If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:
run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }
Or, use a case statement:
run_some_command; ec=$? # grab the exit code into a variable so that it can
# be reused later, without the fear of being overwritten
case $ec in
0) ;;
1) printf '%s\n' "Command exited with non-zero"; exit 1;;
*) do_something_else;;
esac
Related answer about error handling in Bash:
Raise error in a Bash script
If you are writing a function – which is always preferred – you can propagate the error like this:
function()
{
if <command>; then
echo worked
else
return
fi
}
Now, the caller can do things like function && next as expected! This is useful if you have a lot of things to do in the if block, etc. (otherwise there are one-liners for this). It can easily be tested using the false command.
Using Z shell (zsh) you can simply use:
if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi
When using Bash and set -e is on, you can use:
false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi
This might only be useful in a limited set of use-cases, I use this specifically when I need to capture the output from a command and write it to a log file if the exit code reports that something went wrong.
RESULT=$(my_command_that_might_fail)
if (exit $?)
then
echo "everything went fine."
else
echo "ERROR: $RESULT" >> my_logfile.txt
fi
you can just add this if statement:
if [ $? -ne 0 ];
then
echo 'The previous command was not executed successfully';
fi
Below test scripts below work for
simple bash test commands
multiple test commands
bash test commands with pipe included:
if [[ $(echo -en "abc\n def" |grep -e "^abc") && ! $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
if [[ $(echo -en "abc\n def" |grep -e "^abc") && $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
The output is:
pipe true
pipe false

shell bash - return code

Is it possible to run a command to redirect output and standard error in a file and know the return code of the command ?
./COMMANDE.sh 2>&1 | tee -a $LOG_DIRECTORY/$LOG_FILE
if [ $? = 0 ]; then
echo "OK"
else
echo "KO"
exit 1
fi
Currently, I get the return code of the tee command, I want to recover that of COMMANDE.sh.
You want PIPESTATUS.
./COMMANDE.sh 2>&1 | tee -a $LOG_DIRECTORY/$LOG_FILE
if [ ${PIPESTATUS[0]} = 0 ]; then
echo "OK"
else
echo "KO"
exit 1
fi
The index into the array ([0]) is the index of the command in the pipe chain just executed (./COMMANDE.sh). ${PIPESTATUS[1]} would be the tee.

Shell Script: Exit call not working on using back quotes

I am using exit 1 to stop a shell script execution when error occured.
Shell Script
test() {
mod=$(($1 % 10))
if [ "$mod" = "0" ]
then
echo "$i";
exit 1;
fi
}
for i in `seq 100`
do
val=`test "$i"`
echo "$val"
done
echo "It's still running"
Why it's not working?. How can I stop the shell script execution?
The shell that exit is exiting is the one started by the command substitution, not the shell that starts the command substitution.
Try this:
for i in `seq 100`
do
val=`test "$i"` || exit
echo "$val"
done
echo "It's still running"
You need to explicitly check the exit code of the command substitution (which is passed through by the variable assignment) and call exit again if it is non-zero.
Incidentally, you probably want to use return in a function rather than exit. Let the function caller decide what to do, unless the error is so severe that there is no logical alternative to exiting the shell:
test () {
if (( $1 % 10 == 0 )); then
echo "$i"
return 1
fi
}
The exit command terminates only the (sub)shell in which it is executed.
If you want to terminate the entire script, you have to check the exit status
($?) of the function and react accordingly:
#!/bin/bash
test() {
mod=$(($1 % 10))
if [ "$mod" -eq "0" ]
then
echo "$i";
exit 1;
fi
}
for i in `seq 100`
do
val=`test "$i"`
if [[ $? -eq 1 ]]
then
exit 1;
fi
echo "$val"
done
echo "It's still running"

Resources