Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a Bash alias that takes a parameter?

Tags:

alias

bash

I used to use CShell (csh), which lets you make an alias that takes a parameter. The notation was something like

alias junk="mv \\!* ~/.Trash" 

In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.

like image 674
Hello Avatar asked Aug 20 '11 12:08

Hello


People also ask

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.

How do I pass a parameter to alias in Linux?

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.


1 Answers

Bash alias does not directly accept parameters. You will have to create a function.

alias does not accept parameters but a function can be called just like an alias. For example:

myfunction() {     #do things with parameters like $1 such as     mv "$1" "$1.bak"     cp "$2" "$1" }   myfunction old.conf new.conf #calls `myfunction` 

By the way, Bash functions defined in your .bashrc and other files are available as commands within your shell. So for instance you can call the earlier function like this

$ myfunction original.conf my.conf 
like image 82
arunkumar Avatar answered Sep 28 '22 19:09

arunkumar