传递一个别名作为函数参数 [英] Passing an alias as a function parameter

查看:124
本文介绍了传递一个别名作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新人在这里bash脚本编程。舾装过我的.bash_profile中一些有用的功能来查询一些MySQL数据库,但我有麻烦的bash承认传递的参数作为别名。详情参见下面的:

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';"
}

使用例子:

findfield %field% mpc

在哪里MPC是指向数据库来查询的别名。这种用法返回一个错误:

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

-bash: mpc: command not found

上述功能,如果我在的地方$ 2根本就很难code MPC工程 - ?那么,为什么不是用别名工作作为一个参数,而不是

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?

推荐答案

别名默认情况下不会在非交互式壳工作。您可以更改与禁用了javascript -s expand_aliases ,但我不知道它会有所帮助。

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.

您需要评估的另一层。到时候的bash替换完一切,要执行的命令,它认为的MPC作为一个字符串。您可以修复这种变化与评估,但你需要维护其他参数和如果有人通过一些调皮?这就是为什么使用eval一般是令人难以接受的。有时是不可避免的,但:

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

反正你也需要修复在SQL中引用或领域将永远不会得到扩展。语法高亮这里使这个显而易见的。一个简单的方法是只是一对附上$ 1,所以你有效,直到它被传递的字符串分割成三个。

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.

这篇关于传递一个别名作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆