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?
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.
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.
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.
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.
Try defining a function in ~/.profile.
function greplogs(){ grep "$1" */logs/*.log }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With