Musical Shore
Musical Shore

Reputation: 1381

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. I have looked at a number of solutions on stackoverflow, but they aren't working. 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

Upvotes: 0

Views: 45

Answers (1)

Dale_Reagan
Dale_Reagan

Reputation: 2061

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', i.e. 'tf_' # test function.

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':

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

## try 'egrep' if above not working

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

You save the above to a file, i.e. /tmp/test.functions.sh
Then use 'source' to test...

source /tmp/test.functions.sh # edit and repeat until working

Once ready/working, add to your profile.

:)
Dale

Upvotes: 1

Related Questions