How to exit a function in bash

前端 未结 3 1773
猫巷女王i
猫巷女王i 2021-01-30 15:18

How would you exit out of a function if a condition is true without killing the whole script, just return back to before you called the function.

Example



        
相关标签:
3条回答
  • 2021-01-30 15:57

    If you want to return from an outer function with an error without exiting you can use this trick:

    do-something-complex() {
      # Using `return` here would only return from `fail`, not from `do-something-complex`.
      # Using `exit` would close the entire shell.
      # So we (ab)use a different feature. :)
      fail() { : "${__fail_fast:?$1}"; }
    
      nested-func() {
          try-this || fail "This didn't work"
          try-that || fail "That didn't work"
      }
      nested-func
    }
    

    Trying it out:

    $ do-something-complex
    try-this: command not found
    bash: __fail_fast: This didn't work
    

    This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

    Note that this causes the outermost function to return 1.

    0 讨论(0)
  • 2021-01-30 15:58

    Use return operator:

    function FUNCT {
      if [ blah is false ]; then
        return 1 # or return 0, or even you can omit the argument.
      else
        keep running the function
      fi
    }
    
    0 讨论(0)
  • 2021-01-30 16:12

    Use:

    return [n]
    

    From help return

    return: return [n]

    Return from a shell function.
    
    Causes a function or sourced script to exit with the return value
    specified by N.  If N is omitted, the return status is that of the
    last command executed within the function or script.
    
    Exit Status:
    Returns N, or failure if the shell is not executing a function or script.
    
    0 讨论(0)
提交回复
热议问题