Exit bash script on error in loop

Tony Arnold tony.arnold at manchester.ac.uk
Thu Sep 12 19:21:28 UTC 2013


Johnny,

On 12/09/13 19:19, Johnny Rosenberg wrote:
> 
> I can't make exit work as I thought it would work…
> 
> #!/bin/bash
> 
> Title="Error"
> ERROR="Something bad happened."
> 
> while [ something ]; do
>     if [[ something_bad ]]; then
>         yad --title "${Title}" \
>             --image=error \
>             --text "${ERROR}" \
>             --no-buttons \
>             --timeout 5 &
>         exit 1
>     fi
> done
> more_statements
> 
> # End of code
> 
> The problem is that even if something_bad happens, more_statements are
> executed. The yad error messages is displayed as expected, though.
> 
> (yad is a dialogue, similar to zenity, or even a zenity fork, I think –
> yad=Yet Another Dialogue)
> 
> So it seems like only the loop is exited when exit 1 is executed, not
> the whole script. So how can I exit the whole script if something bad
> happens inside a loop? I'd prefer a solution that doesn't make it
> necessary to rewrite the script from scratch…

Odd. The following works for me. I'm on 13.04. Cannot find yad in the
repositories. Where did you get it from? And are you definitely using
bash for your script?

#!/bin/bash

i=4
while [ "$i" -gt "0" ]; do
    echo "$i - Hello"
    if [ "$i" -eq "2" ]; then
        zenity --error --text "Oh no! i=3"
        exit 1
    fi
    let i=i-1
done
echo "Oops!"


Regards,
Tony.
-- 
Tony Arnold,                        Tel: +44 (0) 161 275 6093
Head of IT Security,                Fax: +44 (0) 705 344 3082
University of Manchester,           Mob: +44 (0) 773 330 0039
Manchester M13 9PL.                 Email: tony.arnold at manchester.ac.uk




More information about the ubuntu-users mailing list