Writing try catch finally in shell

后端 未结 6 1068
说谎
说谎 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:42

    Another way to do it would be:

    set -e;  # stop on errors
    
    mkdir -p "$HOME/tmp/whatevs"
    
    exit_code=0
    
    (
      set +e;
      (
        set -e;
        echo 'foo'
        echo 'bar'
        echo 'biz'
      )
      exit_code="$?"
    )
    
    rm -rf "$HOME/tmp/whatevs"
    
    if [[ "exit_code" != '0' ]]; then
       echo 'failed';
    fi 
    

    although the above doesn't really offer any benefit over:

    set -e;  # stop on errors
    
    mkdir -p "$HOME/tmp/whatevs"
    
    exit_code=0
    
    (
        set -e;
        echo 'foo'
        echo 'bar'
        echo 'biz'
        exit 44;
        exit 43;
    
    ) || {
       exit_code="$?"  # exit code of last command which is 44
    }
    
    rm -rf "$HOME/tmp/whatevs"
    
    if [[ "exit_code" != '0' ]]; then
       echo 'failed';
    fi 
    

提交回复
热议问题