Saturday, November 5, 2022

Using Aliases in Linux

Earlier, I talked about how using the command line in Linux can save a lot of time and effort in your day to day computing tasks. But, there’s a very powerful function in Linux, called “alias”, that can save you even more time and effort.

command-alias.jpg

What it boils down to is this: with the alias command, you can take a more complicated command in Linux, with it’s potentially extensive assortment of options, and turn it into one simple command that means something to you. It’s very similar to creating a macro in Microsoft Office, or something like that, only much more powerful.

For example, in my previous entry regarding the command line, I demonstrated a way that I burn movie files to DVDs. It was:

growisofs -use-the-force-luke=tty -Z /dev/sr0 -J -r -speed=8 -dvd-compat -pad -graft-points my-movie-file.mp4

That’s quite a long command to have to type in correctly every time I want to burn a file to DVD. But, with alias, I can turn that all into one command like this:

dvdburn my-movie-file.mp4

By doing this, I free myself from having to remember all of the option variables, as well as ensuring I typed them all in correctly ever time I use the command. But, most importantly, I save myself some time.

To use alias to make this happen, I typed in this command:

alias dvdburn='growisofs -use-the-force-luke=tty -Z /dev/sr0 -J -r -speed=8 -dvd-compat -pad -graft-points'

Notice that I left off the name of the file I wanted to burn. I just associated the command(s) themselves to the alias “dvdburn”. Now, Linux knows that when I type dvdburn, it is to replace that with the command I have specified within the single quotation marks.

In this example, Linux will remember this alias until I log-off the system. But, what if you want this alias to be remembered ever time you log in to the computer? You simply add the alias command to your .bashrc configuration file.

Use what ever text editor you prefer, open up the file “.bashrc”, then simply append your alias command.

alias-bashrc.png

In this example, you can see that I have set up four aliases in my .bashrc file.

If you ever wish to list all of the aliases that have been defined, simply type “alias” all on its own and press ENTER. You will see both the aliases you’ve set up, as well as any that have been assigned to the system, defined by your specific Linux distribution.

Aliases are not only limited to one command, either. If you wish Linux to carry out more than one task when you execute an alias, simply use the “&” to paste the commands together. Like this:

alias photojpgs='cd /home/david/photos & ls *.jpg'

In this example, when I execute the command “photojpgs”, Linux with take me into my Photos directory, then list all of the JPGs within it.

With the use of aliases, even the most complicate commands can be rendered down into time saving, easily remembered one word alternatives.
[tag]linux, how-to[/tag]