Passing an alias as a function parameter

只谈情不闲聊 提交于 2019-12-11 09:03:15

问题


Newcomer to bash scripting here. Been outfitting my bash_profile with some useful functions to query some mysql databases, but am having trouble getting bash to recognize a passed parameter as an alias. See below for details:

function findfield() {
    $2 -e
    "SELECT TABLE_NAME,TABLE_SCHEMA,COLUMN_NAME AS 'Matched Field'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '$1';"
}

example usage:

findfield %field% mpc

Where mpc is an alias that points to the database to query. This usage returns an error:

-bash: mpc: command not found

The above function works if I simply hardcode mpc in place of $2--so why wouldn't it work with an alias as a parameter instead?


回答1:


Aliases don't work by default in noninteractive shells. You can change that with shopt -s expand_aliases, but I'm not sure it will help.

You need another layer of evaluation. By the time bash finishes substituting everything and wants to run the command, it thinks of "mpc" as a string. You can fix this change that with eval, but then you need to safeguard the other parameters and what if someone passes something naughty? This is why the use of eval is generally frowned upon. Sometimes it is unavoidable though:

$ run() { $1; }
$ alias alal=uname
$ run whoami
lynx
$ run alal
bash: alal: command not found
$ run() { shopt -s expand_aliases; $1; shopt -u expand_aliases; }
$ run alal
bash: alal: command not found
$ run() { shopt -s expand_aliases; eval $1; shopt -u expand_aliases; }
$ run alal
Linux

Anyway, you also need to fix the quoting in the sql or the field will never get expanded. The syntax highlighting here makes this obvious. A simple way is just to enclose $1 in a pair of ", so you effectively split the string into three until it is passed on.




回答2:


You may need to add an extra line in your bash_profile file:

function myalias_func()
{
        some code here with different variables $1, $2...
}
alias myalias=myalias_func

That is, try including the line

alias findfield=findfield

and it should work then.



来源:https://stackoverflow.com/questions/15455757/passing-an-alias-as-a-function-parameter

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