tags:

views:

78

answers:

2

I end up typing

grep -Rni pattern .

and awful lot. How do I make this into an alias like

alias gr='grep -Rni $@ .'

Running that gives:

$ gr pattern
grep: pattern: No such file or directory

Even though the alias looks fine:

$ type gr
gr is aliased to `grep -R $@ .'

It seems that the $@ and the . get swapped when it's actually executed.

+5  A: 

make a function instead of alias. Save it in a file eg mylibrary.sh and whenever you want to use the funtion, source the file

eg mylibrary.sh

myfunction(){
 grep -Rni ...
}

#!/bin/bash
source mylibrary.sh
myfunction 
ghostdog74
sweet! any idea why it has to be a function instead of an alias?
numerodix
inside a function, you can do many other things. eg Flow control. you can also pass in arguments to a function. Its not that easy with aliases. In principle, use alias if your commands are short and simple, otherwise, use functions.
ghostdog74
+5  A: 

Try this:

$ alias gr='grep -Rnif /dev/stdin . <<<'
$ gr pattern
./path/file:42:    here is the pattern you were looking for

This also works:

$ alias gr='grep -Rnif - . <<<'
Dennis Williamson
+1 for here string fu.
Janek Bogucki
Wow! That is cool.
sixtyfootersdude