开发者

Bash Alias with Arguments is failing [duplicate]

开发者 https://www.devze.com 2023-03-15 10:59 出处:网络
This question already has answers here: Make a Bash alias that takes a parameter? (24 answers) Closed 1 year ago.
This question already has answers here: Make a Bash alias that takes a parameter? (24 answers) Closed 1 year ago.

I run the following command to search for text in files and display a pretty output:

$ grep -rnI "SEARCHTERM" . | sed 's/\:\s\+/\:\n/g'
./path/filename.php:LINENUMBER:
This line contains SEARCHTERM

But when I try to run it as an alias I get an error:

$ alias lookfor="grep -rnI '\\!^' . | sed 's/\:\s\+/\:\n/g'"
$ lookfor SEARCHTERM
sed: can't read SEARCHTERM: No such file or directory

Any thoughts as to why my alias is failing? I'm sure it's some sort of q开发者_JS百科uoting issue...


Bash (annoyingly, IMHO) doesn't support arguments for aliases. Instead, I'd suggest writing what you want as a function instead (which are much more powerful):

lookfor() {
  grep -rnI '\\!^' "$@" | sed 's/\:\s\+/\:\n/g'
}

Functions in the long run are better anyway... They'll let you expand it for error handling, etc, later if you like.


I ended up creating a ~/bin folder, and placing an executable file in there named lookfor, with the following content:

#!/bin/sh
grep -rnI "$1" . | sed 's/\:\s\+/\:\n/g'

The ~/bin folder is already acknowledged by my distro as being in the PATH, but for those who don't have this automatically set, you can add it to your PATH by putting the following in your ~/.bashrc:

if [ -d ~/bin ] ; then
    PATH=~/bin:"${PATH}"
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号