Writing try catch finally in shell

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

    I often end up with bash scripts becoming quite large, as I add additional options, or otherwise change them. When a bash-script contains a lot of functions, using 'trap EXIT' may become non-trivial.

    For instance, consider a script invoked as

    dotask TASK [ARG ...]
    

    where each TASK may consists of substeps, where it is desirable to perform cleanup in between.

    In this case, it is helpful to work with subshells to produce scoped exit traps, e.g.

    function subTask (
        local tempFile=$(mktemp)
        trap "rm '${tempFile}'" exit
        ...
    )
    

    However, working with subshells can be tricky, as they can't set global variables of the parent shell.

    Additionally, it is often inconvenient to write a single exit trap. For instance, the cleanup steps may depend on how far a function came before encountering an error. It would be nice to be able to make RAII style cleanup declarations:

    function subTask (
        ...
        onExit 'rm tmp.1'
        ...
        onExit 'rm tmp.2'
        ...
    )
    

    It would seem obvious to use something like

    handlers=""
    function onExit { handlers+="$1;"; trap "$handlers" exit; }
    

    to update the trap. But this fails for nested subshells, as it would cause premature execution of the parent shell's handlers. The client code would have to explicitly reset the handlers variable at the beginning of the subshell.

    Solutions discussed in [multiple bash traps for the same signal], which patch the trap by using the output from trap -p EXIT will equally fail: Even though subshells don't inherit the EXIT trap, trap -p exit will display the parent shell's handler so, again, manual resetting is needed.

提交回复
热议问题