How I can make alias called when it's called by a variable

亡梦爱人 提交于 2019-12-06 10:52:50

问题


I added an alias:

$ alias anyalias="echo kallel"

If I execute:

$ anyalias
kallel

it executes the echo command without any problem.

Now, if I define a variable in this way:

$ var="anyalias"

and then execute with this way:

$  $var
-ash: anyalias: not found

Then I got a shell error.

How I can make $var running the command defined in the anyalias alias?

I m not looking to change the way of calling $var. But I m looking for a way of changing the definition of the alias or export it.


回答1:


Instead of alias consider using function:

anyfunc() { echo "kallel"; }
v=anyfunc
$v
kallel

Safer is to store the call of function in an array (will store arguments also, if needed):

var=(anyfunc)
"${var[@]}"
kallel



回答2:


That's because alias expansion is performed previous to parameter expansion:
Command-line Processing

As you can see, you can go through the process again with eval, which is not recommended.
Instead, you can use some alternatives as the one by @anubhava.


Example

$ alias anyalias="echo kallel"
$ var=anyalias
$ $var
bash: anyalias: command not found
$ eval $var
kallel

Again, use eval carefully. It's just to illustrate the expansion process.



来源:https://stackoverflow.com/questions/27191119/how-i-can-make-alias-called-when-its-called-by-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!