Table of Contents

Bash Alias

Aliases are great way to run Bash commands and scripts quickly.

Set Alias In Bash

Creating aliases in bash is very straight forward. The syntax is as follows:

alias alias_name="command_to_run"

Let us create an alias for the following list command...

ls -lrt

Here is how you do it...

alias l='ls -lrt'

´╗┐Note: You need to add above alias in the ~/.bashrc file to make sure that alias is available next time on login or when you open a new xterm.

Bash Alias With Arguments

To create complex aliases, we need aliases to which we can provide command line arguments. Let us start with following Bash command...

ls -ld * | egrep home

In the above command, we are listing all the directories first and then piping the output to "egrep home" command. In all, we are trying to find the directories whose name contains "home"

If we want to set the alias for above command, the alias should be able to take the argument which is "home" in our case. Let us see how we can do that...

alias lg='ls -ld * | egrep $1'

Note in above alias, $1 represents the argument variable. Now we can run above command with our alias like this...

lg home

Well we can also set aliases for Bash functions. Bash functions are useful to include multiple commands.

Bash Alias With Bash Functions

Let us create a simple Bash function to "cd" a directory and then display the contents of it.

cdls ()
{
  cd "$1";
´╗┐  ls -lrt "$1"
}  

Copy the above code and paste it in your Bash shell. You need to source ~/.bashrc if you pasted the code in to your ~/.bashrc file.

Now you can run the above alias like this in your bash shell...

cdls

You should notice that your directory changed and see the contents of the directory when "ls -lrt" is executed.

Related Posts

1
2
3
4
5