How to exit if a command failed?

后端 未结 8 1435
猫巷女王i
猫巷女王i 2020-11-28 01:18

I am a noob in shell-scripting. I want to print a message and exit my script if a command fails. I\'ve tried:

my_command && (echo \'my_command failed         


        
相关标签:
8条回答
  • 2020-11-28 02:03

    The trap shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can say trap "your shell code" ERR and the shell code will be executed any time a command returns a non-zero status. For example:

    trap "echo script failed; exit 1" ERR

    Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch false | true.

    0 讨论(0)
  • 2020-11-28 02:04

    Provided my_command is canonically designed, ie returns 0 when succeeds, then && is exactly the opposite of what you want. You want ||.

    Also note that ( does not seem right to me in bash, but I cannot try from where I am. Tell me.

    my_command || {
        echo 'my_command failed' ;
        exit 1; 
    }
    
    0 讨论(0)
提交回复
热议问题