简体   繁体   English

将别名作为函数参数传递

[英]Passing an alias as a function parameter

Newcomer to bash scripting here. bash脚本编写的新手在这里。 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. 我为bash_profile装备了一些有用的功能来查询一些mysql数据库,但是让bash将传递的参数识别为别名时遇到了麻烦。 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. 其中,mpc是指向要查询的数据库的别名。 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? 如果我只是简单地用$ 2-代替-2来硬编码mpc,那么上面的函数就起作用了,那为什么不能用别名作为参数来起作用呢?

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. 您可以使用shopt -s expand_aliases ,但不确定是否会有所帮助。

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. 当bash替换完所有内容并想运行命令时,它会将“ mpc”视为字符串。 You can fix this change that with eval , but then you need to safeguard the other parameters and what if someone passes something naughty? 您可以使用eval修复此更改,但是然后需要保护其他参数,如果有人通过调皮的话该怎么办? This is why the use of eval is generally frowned upon. 这就是为什么通常不使用eval的原因。 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. 无论如何,您还需要修复sql中的引用,否则该字段将永远不会扩展。 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. 一种简单的方法是将$ 1括在一对“中,这样就可以有效地将字符串分成三部分,直到将其传递为止。

You may need to add an extra line in your bash_profile file: 您可能需要在bash_profile文件中添加一行:

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. 然后它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM