【问题标题】:In Bash, it is okay for a variable and a function to have the same name?在 Bash 中,变量和函数可以同名吗?
【发布时间】:2012-10-06 03:20:27
【问题描述】:

我的 ~/.bashrc 中有以下代码:

date=$(which date)
date() {
  if [[ $1 == -R || $1 == --rfc-822 ]]; then
    # Output RFC-822 compliant date string.
    # e.g. Wed, 16 Dec 2009 15:18:11 +0100
    $date | sed "s/[^ ][^ ]*$/$($date +%z)/"
  else
    $date "$@"
  fi
}

据我所知,这很好用。是否有理由避免使用同名的变量和函数?

【问题讨论】:

    标签: bash variable-names


    【解决方案1】:

    除了令人困惑之外,没关系。此外,它们并不相同:

    $ date=/bin/ls
    $ type date 
    date is hashed (/bin/date)
    $ type $date 
    /bin/ls is /bin/ls
    $ moo=foo
    $ type $moo 
    -bash: type: foo: not found
    $ function date() { true; }
    $ type date 
    date is a function
    date () 
    { 
    true*emphasized text*
    }
    
    $ which true 
    /bin/true
    $ type true
    true is a shell builtin
    

    每当您键入命令时,bash 都会在三个不同的位置查找该命令。优先级如下:

    1. shell 内置函数(帮助)
      • shell 别名(帮助别名)
      • shell 函数(帮助函数)
    2. 来自 $PATH 的散列二进制文件(首先扫描“最左侧”文件夹)

    变量以美元符号为前缀,这使得它们与上述所有变量都不同。与您的示例进行比较: $date 和 date 不是一回事。因此,变量和函数实际上不可能有相同的名称,因为它们具有不同的“命名空间”。

    您可能会觉得这有点令人困惑,但许多脚本在文件顶部定义了“方法变量”。例如

    SED=/bin/sed
    AWK=/usr/bin/awk
    GREP/usr/local/gnu/bin/grep
    

    通常的做法是用大写字母输入变量名。这对两个目的很有用(除了减少混淆之外):

    1. 没有 $PATH
    2. 检查所有“依赖项”是否可运行

    你不能这样检查:

    if [ "`which binary`" ]; then echo it\'s ok to continue.. ;fi
    

    因为如果二进制文件还没有被散列(在路径文件夹中找到),这会给你一个错误。

    【讨论】:

      【解决方案2】:

      由于您总是必须使用$ 来取消引用 Bash 中的变量,因此您可以随意使用任何您喜欢的名称。

      不过,请注意覆盖全局变量。

      另请参阅:

      http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html

      【讨论】:

        【解决方案3】:

        使用变量的替代方法:使用 bash 的 command 关键字(请参阅 the manual 或在提示符下运行 help command):

        date() {
            case $1 in
                -R|--rfc-2822) command date ... ;;
                *) command date "$@" ;;
            esac
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-28
          • 2011-06-16
          • 2014-04-03
          • 1970-01-01
          • 2019-05-17
          • 1970-01-01
          相关资源
          最近更新 更多