Linux: Alias with Variables / Arguments

Objective: The alias command can be used to launch any command or a group of commands (inclusive of any options, arguments and redirection) by entering a pre-set string. But how to pass an argument to alias or let an alias handle a variable?

Let’s look at a normal alias definition. Let’s say that you want to use ‘ll‘ to run ‘ls -l‘. This is how you define the alias.

Alias with Arguments

Now, let’s say that you want to list the last two modified files in a specific directory. You could use the following command to list the two latest files based on modification date.

To define the above command as an alias which takes in a directory path, we can use the following syntax.

We have to define a function within alias to achieve our goal. Note the use of semicolons after the tail command and after the closing brace. You can run the alias like this.

Alias with Variables

Let’s say you have a variable called BACKUP_DIR that points to a directory. You need to make a tar gzip backup of that directory and you need to touch a file once you are done. To do that, you will need to run:

To use an alias for the above command, use one of the following syntax. One uses single quotes and another uses double quotes with escape strings.

After defining the alias, make sure that the variable BACKUP_DIR is not interpreted. The variable should be printed without being interpreted by the shell. You can verify this by running:

If the output is something like the one below (BACKUP_DIR is replaced by “/path/to/backup/directory“, then most probably you did not define the alias properly. Check the quotes and make sure the variables are escaped properly.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }