【问题标题】:Is there a return keyword in bash?bash中是否有return关键字?
【发布时间】:2016-03-11 03:48:25
【问题描述】:

在下面的代码中,我需要在第一个 if 语句中使用 return 关键字。我需要在 echo.b 之后退出函数

push() {
  a=$1
  b=$2
  if [ $# -eq 0 ]
  then
     echo "Enter git shortname for first argument"
  fi

  if [ $# -eq 1 ]
  then
      b=$(timestamp)
  fi
  git add -A .
  git commit -m $b
  git push $a
  echo "push() completed."
}

研究

谷歌拉起SO article

【问题讨论】:

    标签: git bash


    【解决方案1】:

    重写它,使其始终在底部退出。使用嵌套的 if 构造,这样你就不必在中间退出。

    【讨论】:

    • else 语句是一种方法
    【解决方案2】:

    BASH 确实有 return,但您的函数中可能不需要它。您可以使用:

    push() {
      a="${1?Enter git shortname for first argument}"
    
      [[ $# -eq 1 ]] && b=$(timestamp)
      b=$2
    
      git add -A .
      git commit -m $b
      git push $a
      echo "push() completed."
    }
    

    a="${1?Enter git shortname for first argument}" 如果您不向其传递任何参数,将自动从函数返回并显示给定的错误消息。

    【讨论】:

      【解决方案3】:

      bash 的return 声明有什么问题?

      push() {
        a=$1
        b=$2
        if [ $# -eq 0 ]
        then
           echo "Enter git shortname for first argument"
           return
        fi
      
        if [ $# -eq 1 ]
        then
            b=$(timestamp)
        fi
        git add -A .
        git commit -m $b
        git push $a
        echo "push() completed."
      }
      

      【讨论】:

        【解决方案4】:
        push() {
          local a="$1" b="$2" #don't overwrite global variables
          [ "$#" -eq 0 ] && { 
            1>&2 echo "Enter git shortname for first argument" #stderr
            return 64 #EX_USAGE=64
          }
          : "${b:=`timestamp`}" #default value
          git add -A .
          git commit -m "$b"  #always quote variables, unless you have a good reason not to
          git push "$a"
          1>&2 echo "push() completed."
        }
        

        如果您想利用更快的启动时间,上述内容应在dash 和bash 中运行。

        为什么引用?

        如果您不引用,变量将根据 $IFS 中的字符进行拆分,默认情况下是 空格、换行符和tab 字符。此外,未引用变量内容中的 星号 是 glob 扩展的。通常,您既不需要拆分也不需要全局扩展,您可以通过双引号来取消订阅此行为。

        我认为默认引用是一个很好的做法,并在您不引用时评论案例,因为您真的想要在那里拆分或通配。

        (Bash 不会在分配中拆分或全局扩展,因此local a=$1 在bash 中是安全的,但是其他shell(最突出的是dash)可以。a="$1" 是超安全的,与变量在其他地方的行为如何,并且在 shell 之间非常可移植。)

        【讨论】:

        • 我添加了local,因为我听说 JS 在严格模式之前存在全局污染......但是为什么我应该引用变量。那有什么作用?
        • @cadegalt 感谢您接受答案。我已经添加了关于为什么引用是一种好习惯的解释。
        猜你喜欢
        • 1970-01-01
        • 2016-08-09
        • 1970-01-01
        • 1970-01-01
        • 2011-08-01
        • 2014-12-24
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        相关资源
        最近更新 更多