How to create a bash alias with arguments

It comes in handy if we can shorten some of the common sets of commands, or even multiline commands as a shortcut.

The solution is called aliases. Let’s explore the ways and see how easy it is to create bash aliases on the fly!

Here is a way to create a bash alias with arguments.

myecho(){ echo $@; }
alias mycommand='myecho'

We have created:

  • A function myecho, which will echo all arguments.
  • An alias mycommand for calling that function.

Example #1. A bash alias with 1 argument

dev@codetryout:~/sample-git$ myecho(){ echo $@; }
dev@codetryout:~/sample-git$ alias mycommand='myecho'
dev@codetryout:~/sample-git$ 
dev@codetryout:~/sample-git$ mycommand TESTING
TESTING
dev@codetryout:~/sample-git$ 
bash alias with multiple arguments

Example #2. A bash alias with multiple arguments

dev@codetryout:~/sample-git$ mycommand arg1 arg2 arg3
arg1 arg2 arg3
dev@codetryout:~/sample-git$ 

Parameters (arguments) passed on to the function can be accessed via standard variables, such as $1, $2, $3, etc.

To make your alias permanently available, you have to add it to your ~/.bashrc or ~/.bash_profile file

Example #3. Expanding the function code

The alias function can be further expanded with more shell logic, for example, here we are trying with printing multiple arguments, each in a new line.

myecho(){   echo $@ | sed 's/ /\n/g';   }

If you are setting aliases in your bash profiles, such as .bashrs or in .bash_profile, make sure to reload to take effect in the current shell.

You can reload the profile file by sourcing them

source ~/.bashrc

I hope, this was helpful, please feel free to let us know if you have questions or comments.