在Bash中,变量和函数具有相同的名称是可以的吗?

时间:2012-10-06 03:20:27

标签: bash variable-names

我的〜/ .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
}

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

3 个答案:

答案 0 :(得分:4)

除了令人困惑之外,它还没问题。此外,它们不一样:

$ 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 builtins(帮助)
    • shell别名(帮助别名)
    • shell函数(帮助函数)
  2. 从$ PATH('最左边'首先扫描的文件夹)中散列二进制文件
  3. 变量以美元符号为前缀,这使它们与上述所有内容不同。要比较你的例子:$ date和date不是一回事。因此,变量和函数的名称实际上并不可能,因为它们具有不同的"名称空间"。

    您可能会发现这有点令人困惑,但许多脚本定义了"方法变量"在文件的顶部。 e.g。

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

    常见的事情是在大写字母中输入变量名称。这有两个目的(除了不那么混乱):

    1. 没有$ PATH
    2. 检查所有"依赖关系"是可以运行的
    3. 你不能这样检查:

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

      因为如果二进制文件尚未进行哈希处理(在路径文件夹中找到),则会出现错误。

答案 1 :(得分:2)

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

谨防覆盖全球,但是。

另见:

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

答案 2 :(得分:2)

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

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