将别名作为函数参数linux bash传递

Ale*_*lex 2 linux bash bash-function

大家好我正在学习如何在linux中使用.bashrc文件,因为我的标题声明我想知道如何使函数将参数识别为别名

我有一个名为home的别名定义为: alias home=$HOME

并且函数定义为

function go(){
cd $1
ls $1
}
Run Code Online (Sandbox Code Playgroud)

但是当我go home 得到的时候

bash: cd: home: No such file or directory ls: cannot access home: No such file or directory

当我想要它去做$ HOME

我将如何实现这一目标?

Alf*_*lfe 5

别名不是单词替换,而是新创建的小命令:

$ alias bla=ls
$ bla
file1
file2
file3
…
Run Code Online (Sandbox Code Playgroud)

因此,它不能以您假设的方式使用.

您可能希望对此使用变量替换:

$ home=$HOME
$ function go() {
  cd "$(eval echo \$"$1")"
}
$ go home
Run Code Online (Sandbox Code Playgroud)

如果您想使用别名,尽管这是滥用行为,请尝试以下方法:

$ alias home=$HOME
$ function go() {
  cd "$(type "$1" | sed -e 's/.*is aliased to .//' -e 's/.$//')"
}
$ go home
Run Code Online (Sandbox Code Playgroud)

  • +1.你可以在bash中使用[variable indirection](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion):`go(){cd"$ {!1}" ; }; 回家 (2认同)