Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exit status a loop in bash

Tags:

linux

bash

shell

I know how to check the status of the previously executed command using $?, and we can make that status using exit command. But for the loops in bash are always returning a status 0 and is there any way I can break the loop with some status.

#!/bin/bash
while true
do
        if [ -f "/test" ] ; then
                break ### Here I would like to exit with some status
        fi

done
echo $?  ## Here I want to check the status.
like image 771
Sriharsha Kalluru Avatar asked Dec 27 '12 18:12

Sriharsha Kalluru


People also ask

How do you check exit status in bash?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.

How do you exit a loop in bash?

Use the break statement to exit a while loop when a particular condition realizes. The following script uses a break inside a while loop: #!/bin/bash i=0 while [[ $i -lt 11 ]] do if [[ "$i" == '2' ]] then echo "Number $i!" break fi echo $i ((i++)) done echo "Done!"

How do I display exit status in last command?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.


1 Answers

The status of the loop is the status of the last command that executes. You can use break to break out of the loop, but if the break is successful, then the status of the loop will be 0. However, you can use a subshell and exit instead of breaking. In other words:

for i in foo bar; do echo $i; false; break; done; echo $?  # The loop succeeds
( for i in foo bar; do echo $i; false; exit; done ); echo $? # The loop fails

You could also put the loop in a function and return a value from it. eg:

in() { local c="$1"; shift; for i; do test "$i" = "$c" && return 0; done; return 1; }
like image 131
William Pursell Avatar answered Oct 03 '22 17:10

William Pursell