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 ll="ls -l"

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.

$ ls -lt /path/to/directory | tail -2

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

$ alias last2='function _(){ ls -lt $1 |  tail -2; }; _'

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.

$ last2 /path/to/directory

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:

$ tar czvf /path/to/backup/backup.tar.gz $BACKUP_DIR ; touch /path/to/backup/last_backup

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.

$ alias dobackup='tar czvf /path/to/backup/backup.tar.gz $BACKUP_DIR ; touch /path/to/backup/last_backup'
$ alias dobackup="tar czvf /path/to/backup/backup.tar.gz \$BACKUP_DIR ; touch /path/to/backup/last_backup"

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:

$ alias dobackup
alias dobackup='tar czvf /path/to/backup/backup.tar.gz $BACKUP_DIR ; touch /path/to/backup/last_backup'

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.

$ alias dobackup
alias dobackup='tar czvf /path/to/backup/backup.tar.gz /path/to/backup/directory ; touch /path/to/backup/last_backup'

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); }