Writing try catch finally in shell

后端 未结 6 1001
说谎
说谎 2021-01-30 09:52

Is there a linux bash command like the java try catch finally? Or does the linux shell always go on?

try {
   `executeCommandWhichCanFail`
   mv output
} catch {         


        
6条回答
  •  有刺的猬
    2021-01-30 10:32

    I found success in my script with this syntax:

    # Try, catch, finally
    (echo "try this") && (echo "and this") || echo "this is the catch statement!"
    
    # this is the 'finally' statement
    echo "finally this"
    

    If either try statement throws an error or ends with exit 1, then the interpreter moves on to the catch statement and then the finally statement.

    If both try statements succeed (and/or end with exit), the interpreter will skip the catch statement and then run the finally statement.

    Example_1:

    goodFunction1(){
      # this function works great
      echo "success1"
    }
    
    goodFunction2(){
      # this function works great
      echo "success2"
      exit
    }
    
    (goodFunction1) && (goodFunction2) || echo "Oops, that didn't work!"
    
    echo "Now this happens!"
    

    Output_1

    success1
    success2
    Now this happens!
    

    Example _2

    functionThrowsErr(){
      # this function returns an error
      ech "halp meh"
    }
    
    goodFunction2(){
      # this function works great
      echo "success2"
      exit
    }
    
    (functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"
    
    echo "Now this happens!"
    

    Output_2

    main.sh: line 3: ech: command not found
    Oops, that didn't work!
    Now this happens!
    

    Example_3

    functionThrowsErr(){
      # this function returns an error
      echo "halp meh"
      exit 1
    }
    
    goodFunction2(){
      # this function works great
      echo "success2"
    }
    
    (functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"
    
    echo "Now this happens!"
    

    Output_3

    halp meh
    Oops, that didn't work!
    Now this happens!
    

    Note that the order of the functions will affect output. If you need both statements to be tried and caught separately, use two try catch statements.

    (functionThrowsErr) || echo "Oops, functionThrowsErr didn't work!"
    (goodFunction2) || echo "Oops, good function is bad"
    
    echo "Now this happens!"
    

    Output

    halp meh
    Oops, functionThrowsErr didn't work!
    success2
    Now this happens!
    

提交回复
热议问题