Linux Bash Alias Command Tutorial – POFTUT

Linux Bash Alias Command Tutorial

Linux Bash provides some shortcuts about operations. Sometimes we need to run a log and error prone command in the shell. Every time writing or remembering the command is not a feasible way. Bash have alias feature which is used to set some shortcuts about user commands.

alias Command Syntax

The syntax of the alias definition is like below. ALIAS is the shortcut we want to use and can be anything we want but use unique names other than Linux commands. COMMAND is the command we want to use when ALIAS is called.


Create Alias

Commands and variables can be very long. Using long commands and variables become a pain. Bash gives the ability to make some alias for them and use them in a short way. In this example, we will create an alias named mls which is equivalent ls /. Every time we call mls ls / command will be executed.

$ alias mls="ls /"
$ mls
1  bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

Make Alias Persistent

Created alias will be removed after reboot or can not be accessed from different shell sessions. We generally need to make defined aliases persistent. In order to make alias persistent, we generally use .bashrc file which is located in the user home directory. We can add our alias named mls to the .bashrc of the current user with the following command.

$ echo "alias mls='ls /'" >> ~/.bashrc

If we want to make alias available to the all system users we should add this elias to the system wide bash configuration file /etc/bash.bashrc or similar name file.

LEARN MORE  How To Run Java Application From Command Line with java Command with Command Line Arguments?

Alias Parameters

Linux bash and similar shells provide a parameter mechanism to make dynamically provide data. We can use this mechanism to make our alias dynamic. In bash $1 specifies the first parameter $2 specifies second, ..In this example, we will define our alias named mls which accept a single parameter. This parameter provided to the ls command as path. If we do not provide a parameter it will act as space.

$ alias mls='ls $1'
Alias Parameters
Alias Parameters

Multiline Alias Command

In bash ; used to delimit the commands. It is generally used to provide multiple commands in a single line. We can use t; in alias too. In this example, we will list the root directory and then print some text with multiple commands in the alias.

$ alias mls='ls /;echo "Root directory listed";'

Leave a Comment