简体   繁体   English

将参数传递给bash函数会导致错误

[英]Passing a parameter to a bash function results in error

I am trying to pass a parameter on the command line to a function defined in ~/.bash_profile. 我试图将命令行上的参数传递给〜/ .bash_profile中定义的函数。 I have looked at a number of solutions on stackoverflow, but they aren't working. 我看过许多关于stackoverflow的解决方案,但是它们不起作用。 Basically, the format is this: 基本上,格式是这样的:

function rgrep  { /usr/bin/grep -rl '$@' . | /usr/bin/grep -v 'node_modules' | /usr/bin/grep -v 'bower'; }

However, when I try this: 但是,当我尝试这样做时:

rgrep 'foo'

I get 我懂了

grep: foo: No such file or directory

Usually, if you get your command sequence to 'work' from the command line then it may work as a 'function' - do the commands 'work' from the command line? 通常,如果您从命令行将命令序列设置为“工作”,则该命令序列可以作为“功能”工作-命令行中的命令“工作”吗?

Also, to avoid possible confusion with existing commands, I suggest adding a 'prefix', ie 'tf_' # test function. 另外,为避免与现有命令混淆,我建议添加一个“前缀”,即“ tf _”#测试功能。

You need double quotes - (") instead of (')... I suggest trying something simpler: 您需要双引号-(“)而不是(')...我建议尝试一些更简单的方法:

function tf_rgrep  { grep -rl "$@" . | grep -ve "node_modules|bower" ;}  

For debugging add 'set -x': 要进行调试,请添加“ set -x”:

function tf_rgrep  { set -x; grep -rl "$@" . | grep -ve "node_modules|bower" ; set - ;}   

## try 'egrep' if above not working

function tf_rgrep { set -x; 函数tf_rgrep {set -x; egrep -rl "$@" . egrep -rl“ $ @”。 | | egrep -ve "node_modules|bower" ; egrep -ve“ node_modules | bower”; set - ;} 设置-;}

You save the above to a file, ie /tmp/test.functions.sh 您将以上内容保存到文件,即/tmp/test.functions.sh
Then use 'source' to test... 然后使用“源”进行测试...

source /tmp/test.functions.sh # edit and repeat until working source /tmp/test.functions.sh编辑并重复直到工作

Once ready/working, add to your profile. 准备就绪/工作后,将其添加到您的个人资料。

:) :)
Dale 戴尔

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

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