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 [email protected]; }
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

[email protected]:~/sample-git$ myecho(){ echo [email protected]; }
[email protected]:~/sample-git$ alias mycommand='myecho'
[email protected]:~/sample-git$ 
[email protected]:~/sample-git$ mycommand TESTING
TESTING
[email protected]:~/sample-git$ 
bash alias with multiple arguments

Example #2. A bash alias with multiple arguments

[email protected]:~/sample-git$ mycommand arg1 arg2 arg3
arg1 arg2 arg3
[email protected]:~/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 [email protected] | 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.