Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 脚本中丢失的别名_Bash_Macos_Shell - Fatal编程技术网

Bash 脚本中丢失的别名

Bash 脚本中丢失的别名,bash,macos,shell,Bash,Macos,Shell,当程序在mac上运行时,我想将gnu日期gdate别名为date #!/bin/bash if [[ $(uname) -eq 'Darwin' ]]; then alias date="gdate" echo 'you are on a mac!' type date fi # rest of the program 给定此代码,如果我直接在终端上运行int,它将打印: you are on a mac! date is an alias for gdate 但是如

当程序在mac上运行时,我想将gnu日期
gdate
别名为
date

#!/bin/bash
if [[ $(uname) -eq 'Darwin' ]]; then
    alias date="gdate"
    echo 'you are on a mac!'
    type date
fi
# rest of the program
给定此代码,如果我直接在终端上运行int,它将打印:

you are on a mac!
date is an alias for gdate
但是如果我在打印中像
/test.sh
那样运行脚本本身:

you are on a mac!
date is /bin/date

为什么不从脚本应用别名?

默认情况下,别名不会在非交互式shell中展开。改用函数

if [[ $(name) -eq Darwin ]]; then
   date () { gdate "$@"; }
   echo 'you are on a mac!'
   type date
fi

在许多情况下,使用函数将是正确的解决方案。任何时候,只要有基于函数的解决方案,就可以这样做

但是,有些事情是函数无法完成的,最明显的是与修改调用上下文的位置参数有关,您可以通过启用相应的选项在shell脚本中强制别名扩展:

shopt -s expand_aliases

您必须知道并控制脚本中存在哪些别名,以避免意外行为。

尝试:source test.shIf如果设置
shopt-s expand_别名
,则别名将在非交互式shell中展开,但chepner的答案不仅仅是作为别名替换,它的作用非常大。但是,我必须将
$@
放入参数列表中才能传递给gdate。它只与
@
一起工作吗?不;那是我的错别字<代码>“$@”是必需的。这很好,因为我在与zsh合作,这解决了一些常见的
奇怪行为。