how to make alias to make grep command shorter
Pay attention to the tags on this question. This answer is the correct one given the version of grep
that's included with CentOS 6 is below version 2.11
I don't believe you can do this using just an alias (at least not in the form that you've written it - see @Graeme's answer for an alternative syntax).
NOTE: I'll also mention here that @Graeme's solution though correct does not work on CentOS 5 & 6. I've confirmed this and it does in fact appear to be an issue with the version of grep
(2.11 or older) that's bundled with those distros. The issue appears to be with grep
not, by default, searching STDIN when no path argument is provided with the -r
switch. Running grep -rnIi --color "string"
just hangs indefinitely, attempting to search STDIN.
Aliases cannot take arguments being passed into them. They're more synonymous to a macro where they can get expanded by the shell to something else.
$ alias ll='ls -l'
This can then be used like so:
$ ll
-or-
$ ll somedir
But somedir
isn't passed to ll
, rather ll
is expanded in place to ls -l
and then replaces ll
in your command.
Back to your question
You can use a function in the shell instead. Functions can take arguments.
$ function mygrep { grep -rnIi "$1" . --color; }
You then use it like this:
$ mygrep "blah"
This can actually be an alias. The --color
doesn't have to be at the end, and grep
always searches the current directory with -r
if no directory option is given (at least GNU grep
does). Therefore you can do:
alias mygrep='grep -rnIi --color'
Update
The behaviour of searching the current directory by default was introduced in GNU grep 2.11
. From the changelog:
If no file operand is given, and a command-line -r or equivalent option is given, grep now searches the working directory. Formerly grep ignored the -r and searched standard input nonrecursively. An -r found in GREP_OPTIONS does not have this new effect.
So, on versions >=2.11
of GNU grep
, usage of the alias would be as follows:
mygrep PATTERN [PATH...]
For versions of grep
before this, you would have to specify the path every time @slm's answer using a function is the best way. Although you could achieve the same usage as above by writing the function like this:
mygrep () { grep -rnIi --color "$1" "${2:-.}"; }
Assuming, of course, that there is no requirement for the --color
to be at the end as in the Q...