Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an alias where the arguments go in the middle? [duplicate]

I'm trying to define an alias where the arguments are inserted in the middle, instead of appended to the end.

I tried defining it like this:

alias grep_logs="grep $1 */log/*.log" 

where $1 is the first argument to grep_logs, such that:

grep_logs foo 

would execute the following command:

grep foo */log/*.log 

but instead, it runs the command:

grep foo */log/*.log foo 

which results in the error:

grep: foo: No such file or directory 

Is it possible to do this using an alias or do I need to define a function?

like image 504
sferik Avatar asked Aug 24 '11 20:08

sferik


People also ask

How do you pass arguments to Alias command?

You can replace $@ with $1 if you only want the first argument. This creates a temporary function f , which is passed the arguments. Alias arguments are only passed at the end. Note that f is called at the very end of the alias.

How is an alias to a argument created in a declare section?

Explanation: To declare an alias, the keyword ALIAS is used. Then, the colon sign followed by the name of ALIAS. Then, the name of the object is then specified whose alias is to be created. So, that the duplicate for that object can be created.

Can a bash alias take arguments?

Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.

Can alias have spaces?

Note. If the alias_name contains spaces, you must enclose the alias_name in quotes. It is acceptable to use spaces when you are aliasing a column name. However, it is not generally good practice to use spaces when you are aliasing a table name.


1 Answers

Try defining a function in ~/.profile.

function greplogs(){     grep "$1" */logs/*.log } 
like image 96
Jack Avatar answered Oct 08 '22 13:10

Jack