In a Bash script, how can I exit the entire script if a certain condition occurs?

后端 未结 7 1735
我在风中等你
我在风中等你 2020-11-29 14:30

I\'m writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I\'ll just abort the

7条回答
  •  佛祖请我去吃肉
    2020-11-29 14:53

    I have the same question but cannot ask it because it would be a duplicate.

    The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

    Here is a little script on how to do it:

    #!/bin/bash
    
    boom() {
        while true; do sleep 1.2; echo boom; done
    }
    
    f() {
        echo Hello
        N=0
        while
            ((N++ <10))
        do
            sleep 1
            echo $N
            #        ((N > 5)) && exit 4 # does not work
            ((N > 5)) && { kill -9 $$; exit 5; } # works 
        done
    }
    
    boom &
    f &
    
    while true; do sleep 0.5; echo beep; done
    

    This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

提交回复
热议问题