How to exit if a command failed?

后端 未结 8 1472
猫巷女王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 01:41

    Try:

    my_command || { echo 'my_command failed' ; exit 1; }
    

    Four changes:

    • Change && to ||
    • Use { } in place of ( )
    • Introduce ; after exit and
    • spaces after { and before }

    Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a || not an &&.

    cmd1 && cmd2
    

    will run cmd2 when cmd1 succeeds(exit value 0). Where as

    cmd1 || cmd2
    

    will run cmd2 when cmd1 fails(exit value non-zero).

    Using ( ) makes the command inside them run in a sub-shell and calling a exit from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.

    To overcome this use { }

    The last two changes are required by bash.

提交回复
热议问题