How to exit if a command failed?

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

    I've hacked up the following idiom:

    echo "Generating from IDL..."
    idlj -fclient -td java/src echo.idl
    if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
    
    echo "Compiling classes..."
    javac *java
    if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi
    
    echo "Done."
    

    Precede each command with an informative echo, and follow each command with that same
    if [ $? -ne 0 ];... line. (Of course, you can edit that error message if you want to.)

提交回复
热议问题