How to exit if a command failed?

后端 未结 8 1479
猫巷女王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:50

    Note also, each command's exit status is stored in the shell variable $?, which you can check immediately after running the command. A non-zero status indicates failure:

    my_command
    if [ $? -eq 0 ]
    then
        echo "it worked"
    else
        echo "it failed"
    fi
    

提交回复
热议问题