如何编写bash函数来包装另一个命令? [英] How to write a bash function to wrap another command?
问题描述
我正在尝试为 mysql
命令
如果pwd中存在 .my.cnf
,我想自动将-defaults-file = .my.cnf
附加到命令
If .my.cnf
exists in the pwd, I would like to automatically attach --defaults-file=.my.cnf
to the command
这就是我正在尝试的
function mysql {
if [ -e ".my.cnf" ]; then
/usr/local/bin/mysql --defaults-file=.my.cnf "$@"
else
/usr/local/bin/mysql "$@"
fi
}
想法是,我希望能够像以前一样完全使用 mysql
命令 ,仅在 .my.cnf
文件存在,将其作为参数附加
The idea is, I want to be able to use the mysql
command exactly as I was before, only, if the .my.cnf
file is present, attach it as an argument
问题:这种方法会遇到任何麻烦吗?有更好的方法吗?
Question: Will I run into any trouble with this method? Is there a better way to do it?
如果我手动指定-defaults-file = foo.cnf
,则应使用它代替 .my.cnf
.
If I specify --defaults-file=foo.cnf
manually, that should be used instead of .my.cnf
.
推荐答案
您编写的函数非常好.这是一个触摸式干燥器:
Your function as written is perfectly fine. This is a touch DRYer:
function mysql {
if [ -e ".my.cnf" ]; then
set -- --defaults-file=.my.cnf "$@"
fi
/usr/local/bin/mysql "$@"
}
该 set
命令将my.cnf参数放在命令行参数的开头
That set
command puts your my.cnf argument at the beginning of the command line arguments
仅当该选项尚不存在时:
Only if the option is not already present:
function mysql {
if [[ -e ".my.cnf" && "$*" != *"--defaults-file"* ]]; then
set -- --defaults-file=.my.cnf "$@"
fi
/usr/local/bin/mysql "$@"
}
这篇关于如何编写bash函数来包装另一个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!