By Electric Pilgrim, 28 August, 2023

Linux bash aliases are like personal shorthand we can use in a Linux terminal. Aliases let us create abbreviations of a few characters to represent an entire Linux command, or even several of them. Think of bash aliases as command line macros for Linux.

For instance, here’s an alias to print a sorted list of shell environmental variables:

plaintext   
~/Desktop$ alias prenv="printenv | sort"    # Create the alias   
~/Desktop$ prenv                            # Print sorted env variables   
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus   
DESKTOP_SESSION=xfce   
. . .   
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session3   
XDG_SESSION_TYPE=x11   
XDG_VTNR=7   
~/Desktop$    
 

Aliases obviously save Linux command-liners typing time just because of the fewer characters to type. Usually overlooked with aliases is the amount of time they save by eliminating typing mistakes and user omission/oversight errors that often accompany command line entry. Aliases can save a ton of “do overs.” Depending on typing skills and Linux knowledge, aliases can double or triple command line productivity.

Before we show some cool aliases, please allow us a short digression.

Removing an Alias

During our IT career and ever since, we’ve made a habit of learning how to end an app gracefully our first order of business with any new app. Learning how to use the program has always come second. Yes, it sounds silly, but it occasionally saves embarrassment, a good deal of wasted time fumbling, or, worst case, hard re-booting the PC to escape from trapped-in-app jail.

In that spirit here’s how to completely remove an alias that has become unneeded or that we shouldn’t have made in the first place. Using aliases regularly _will_ result in “alias regret” sooner or later. Guaranteed.

plaintext   
~/Desktop$ unalias badalias      # Pretty simple to remove an alias by name   
 

unalias badalias makes an unwanted alias vanish completely for the duration of your terminal session.

Setting Aliases

How to Create an Alias

Here are the steps to create an alias at the command line. At the prompt, type:

- The word alias followed by a space,   
- The alias name,   
- Followed immediately by an equal sign and double quote,   
- The command string you want the alias to stand in for,   
- And another double quote to close the command string.

An alias is much easier to type than to describe. The first line of the previous example gives a visual of alias creation.

Note 1: Alias names are traditionally lower-cased for ease of typing, but they don’t have to be.

Note 2: An alias definition string never contains another alias name. For instance in the alias definition, alias ls="ls --color=auto", the “ls” to the left of the equals sign is an alias to run a style of list display, but the “ls” to the right of the equals sign refers to the Linux list command itself. Put succinctly, alias definition strings are non-recursive.

Note 3: In online documentation we often see single quotes instead of double quotes used for creating a command alias. The two work slightly differently when creating a new alias. Single quotes alias the raw string, as typed. Double quotes allow for variable substitution into the string as below:

plaintext   
~/Desktop$ alias myalias='$HOME/Desktop'    # Single quote alias string.   
~/Desktop$ alias myalias                    # Display the alias...   
alias myalias='$HOME/Desktop'               # ...no substitution for $HOME.   
~/Desktop$ alias myalias="$HOME/Desktop"    # Double quote the alias string.   
~/Desktop$ alias myalias                    # Display the alias...   
alias myalias='/home/myaccount/Desktop'     # ...$HOME is replaced and alias   
                                           # is then converted to a raw string.   
 

We like the substitution flexibility a double-quoted string offers and there’s rarely any downside to it. If no substitution candidate is present in the double-quoted string, it’s just treated as a raw string, as though it were encased in single quotes. We use double quoted aliases in all the following examples.

Guidelines When Setting New Aliases

First understand that, at the bash command line, entering a defined alias name takes precedence over a Linux command or shell script of the same name. In many/most instances this works to our advantage (see the “Overloading Linux Command Names via Aliases” section below). However, it’s wise to give a bit of thought to the alias name before assigning it.

Stating the obvious, pick a name that’s easy to remember and type rather than going for the fewest characters possible. For instance, in our case above we picked prenv over shorter options because it’s a mnemonic we personally find easy to remember.

If we’re new to Linux and don’t yet know the many Linux commands, we can run which newalias to make sure newalias does not supersede a Linux command we might need later. On the other hand, if we’re a seasoned Linux veteran with boatloads of aliases already, we can run alias newalias (without any assignment) to make sure our new alias won’t overwrite on an alias we already have and use.

Another “gotcha” with aliases is simply remembering to use them. We’re bad for seeing an alias mentioned somewhere on the ’Net, thinking “Oooo… that’s a good one, we could really use that,” adding it to our .bashrc startup file, then forgetting it’s even there. If we genuinely want to improve productivity with aliases, we should review our alias collection every so often and make a conscious effort to practice our aliases until they become automatic.

Lastly, a long-term downside can be falling into “alias dependency.” A computer support tech who tricks out his/her own PC as a giant alias candy store may get to where he can barely function in a standard terminal session. He can no longer “eat the dry dog food” as they say in the biz. At that point said techie makes sure he always has a shell script available via a network or on a flash stick when he visits a cubicle. To quickly load up his special candy-store terminal session so he can avoid playing the fool in front of a user. Just sayin’.

Where to Set an Alias

The examples above and those that follow show aliases set on the command line. This is the way to test new aliases or demonstrate them in articles like this. But know that an alias thus assigned will only last until the end of your terminal session.

Most Linux users, once they confirm an alias works correctly, put their aliases into the .bashrc file. Aliases set in .bashrc will be available in every new terminal session the user starts in his account.

We can, of course, unalias any alias set in the terminal or in .bashrc at any time. We can also comment/remove the alias from .bashrc to remove it from all terminal sessions going forward.

Alias “Helper” Commands Summarized

plaintext   
alias              # Display all aliases currently set in the environment.   
alias myalias      # Display a single alias named 'myalias'.   
unalias -a         # Clears all aliases for the session. Occasionally useful   
                  # but often easiest to just end/restart the terminal session.   
unalias myalias    # Clear a single alias named 'myalias'.   
 

Now for the fun stuff — the types of aliases we might want to create and why. Time to strap ourselves in and get set for some command line pedal-to-the-metal.

Aliases As Personal Shorthand

Using aliases as personal macros or shorthand—that is, as abbreviations for frequently used commands—is certainly the most common use of aliases. Here are some examples, courtesy of Dan Calloway of the WNCLUG, with explanations following:

plaintext   
alias brave="/opt/brave.com/brave/brave"                             # 1   
alias brave="/opt/brave.com/brave/brave >/dev/null 2>&1"             # 1   
alias dt="date"                                                      # 2     
alias ff="/opt/firefox/firefox"                                      # 3   
alias ff="/opt/firefox/firefox >/dev/null 2>&1"                      # 3   
alias edit="nano"                                                    # 4     
alias j="jobs -l"                                                    # 5   
alias l="ls -CF"                                                     # 6   
alias la="ls -A"                                                     # 6   
alias ll="ls -lh"                                                    # 6   
alias ls="ls --color=auto"                                           # 6   
alias ports="sudo netstat -tulanp"                                   # 7   
alias top="atop"                                                     # 8   

1. brave starts the Brave browser installed at /opt/brave.com/brave/brave.                
       
   - Run the alias without arguments, (eg brave) to just open the browser to its home page, or   
   - With one or more links as arguments to open specific pages, as in brave amazon.com en.wikipedia.org.   
   - Sometimes opening a GUI app from the command line can leave messages in the terminal. They require pressing the Enter key a time or two to get a command line prompt again when finished with the GUI app. If this becomes annoying, use the second form of the alias to throw away the messages and return immediately to the prompt.                
           
2. dt displays the current system date on the command line.   
3. ff starts the Firefox browser installed at opt/firefox/firefox. As with brave, this can take optional link arguments, and the second form suppresses unwanted output.   
4. edit starts the nano editor.   
5.j lists jobs running in the terminal.   
6. List commands display the contents of the current working directory in a variety of formats:                
       
   - l using -CF gives a “tight,” file-name-only display and appends a character to indicate file type. Hidden files not included.   
   - la using -A gives a “tight” file-name-only display of all files, including hidden.   
   - ll using -lh gives a column display with human readable file size approximations.   
   - ls using --color=auto gives a tight file-name only display using color to indicate file type.                
            
           
7. ports uses netstat to display current port activity. sudo at the front end of the alias string automatically prompts for an admin password so netstat won’t throw an error.   
8. atop start the atop system resource monitor (assuming atop has been installed).

Here are a few of our own aliases with explanations following:

plaintext   
alias cls="clear"                                                    # 1           
alias ed="codium --unity-launch"                                     # 2   
alias ls="ls --color=auto"                                           # 3   
alias lscol="ls -lh --color=auto"                                    # 3   
alias lscolh="ls -lhA --color=auto"                                  # 3   
alias lssort="ls -lhF | sort -k9,9"                                  # 3   
alias lssorth="ls -lhAF | sort -k9,9"                                # 3   
alias lsblk="lsblk -o NAME,FSTYPE,LABEL,FSAVAIL,FSUSE%,MOUNTPOINT"   # 4    
alias j="clear;julia"                                                # 5   
alias ncal="ncal -Mb"                                                # 6   
alias prenv="printenv | sort"                                        # 7   
alias sudo="sudo -E"                                                 # 8   
 

1. cls clears the terminal screen.   
2. ed launches the vscodium editor. It can take 0-N trailing file name arguments to be edited or created. For example, ed or ed myfile1.txt or ed myfile1.txt myfile2.txt, etc.   
3. These ls aliases all piggy-back on Dan’s ideas. The slightly longer alias names help us remember how they display.                
       
   - ls is the standard “tight” file-name-only display with file type colorization included.   
   - lscol is a column oriented display (one file name per line) with human readable file sizes and file type colorization.   
   - lscolh is a column oriented display with human readable file sizes and file type colorization that includes hidden files.   
   - lssort is a column oriented display with human readable file sizes and file type indication (added symbol at the end of the file name) that is sorted by file name.   
   - lssorth is a column oriented display with human readable file sizes and file type indication that is sorted by file name and includes hidden files.                
            
           
4. lsblk shows attached block devices with our preferred columns displayed. We wish more commands allowed output formatting options like this.   
5. j starts Julia, our favorite programming language, in its interactive command line interface after clearing the screen.   
6. ncal displays a terminal calendar in classic style with the week beginning on Monday. (Shout out to Dan.)   
7. prenv displays all our environmental variables sorted by name.   
8. sudo carries our user environment with us when using `sudo` in front of a command.

Aliases are completely up to personal taste—whatever works best for the Linux user. There’s no “must, must, must” or “should, should, should” here. No Linux Gestapo lurking behind a tree to report command line malfeasance to Big Brother or the Emperor Penguin (Linus Torvalds). We hope these examples stimulate ideas for new aliases the reader can add to his/her PC. They also hint at how aliases can save time, especially time wasted by typing errors or misremembering.

Overloading Linux Command Names via Aliases

Recall that in the “Guidelines When Setting New Aliases” section we said that a defined alias takes precedence over a Linux command or shell script of the same name. In the examples above, we did a good bit of “command overloading” without noting the fact. The aliases brave, ls, lsblk, ncal, and sudo above all overload their respective Linux commands.

The main idea here is that we all have commands we like to run in particular ways. That is, with particular options set. For instance, our lsblk alias above lets us run the command to display attached block devices just as we like to see it _every time we run it_. See below for how our modded lsblk displays.

plaintext   
~/Desktop$ lsblk   # after alias for lsblk command set   
NAME      FSTYPE   LABEL        FSAVAIL FSUSE% MOUNTPOINT   
sda                                               
└─sda1      ext4   Backup        521.1G    67% /media/myaccount/Backup   
nvme0n1                                           
├─nvme0n1p1 ext4   rootMX21       14.5G    45% /   
├─nvme0n1p2 ext4   home             94G    46% /home   
└─nvme0n1p3 swap   swapMX                      [SWAP]   
~/Desktop$    
 

Imagine if we had to type lsblk -o NAME,FSTYPE,LABEL,FSAVAIL,FSUSE%,MOUNTPOINT every time we wanted to run the lsblk command. Eyeow!

An occasional drawback to using alias command overloading comes when we need the command to work differently than our usual preferred way. (Hopefully not that often if we’ve chosen our alias name wisely.) At that point we might be able to add needed options as arguments after the alias and have it work like we currently want. Otherwise unalias mycommandalias is called for.

You may have noticed too how Dan’s ports alias above shoehorned a sudo command in front of netstat. Aliases give us an easy out to save remembering which commands require sudo and also from typing sudo all the time . Ergo, less mistakes, less retyping, less “prompt frustration.”

A good example of “sudo shoehorning” is demonstrated by a set of aliases installed globally by default in MX Linux 21.3:

plaintext   
alias ag="sudo apt-get update;apt-get dist-upgrade"                  # 1   
alias aga="sudo apt-get autoremove"                                  # 2   
alias agc="sudo apt-get clean"                                       # 3   
alias agd="sudo apt-get dist-upgrade"                                # 4   
alias agu="sudo apt-get update"                                      # 5   
 

…where apt-get is the command line interface for the Debian package management system.

1. ag first updates the list of available packages (recommended before any other apt-get commands), then updates installed packages while removing obsolete packages and installing additional dependencies. The semicolon works like a newline in a script. apt-get always require admin privileges (hence the inserted sudo command).   
2. aga removes packages that are no longer needed (aka “orphaned dependencies”) to keep our PC neat and tidy and conserve some space.   
3. agc clears out the local repository of retrieved package files.   
4. agd upgrades installed packages (like upgrade), but removes obsolete packages and installs additional packages to meet new dependencies.   
5. agu resynchronizes the package index files from their sources.

Aliases For Fast Directory Navigation

Let’s face it—we waste gobs of time at the command line jumping from one directory to another in the terminal. And then back again. And then over here. Then over there….

Here’s how Dan improves the time-eating directory navigation problem:

plaintext   
alias 1.="cd .."   
alias 2.="cd ../../"   
alias 3.="cd ../../../"   
alias 4.="cd ../../../../"     
alias 5.="cd ../../../../.."   
 

Whichever of the numbered aliases he selects jumps back (up) that many levels in his file system tree. Dan hasn’t discussed it with us, but our guess is that he uses his various ls aliases mentioned earlier in combination with the above navigation aliases to quickly cruise up and down through his file system hierarchy.

We take a somewhat different approach at our command line. Here are a few of our directory navigation aliases. Note the use of `$HOME` for substituting part of the directory path:

plaintext   
alias .config="cd $HOME/.config"   
alias .fonts="cd $HOME/.fonts"   
alias .icons="cd $HOME/.icons"   
alias .julia="cd $HOME/.julia"   
alias Desk="cd $HOME/Desktop"   
alias Essays="cd $HOME/Writing/Essays"   
alias Scripts="cd $HOME/Sys/Scripts"   
 

The idea here is that by simply typing the sub-directory name we jump to it directly, like so:

plaintext   
~/Desktop$ Scripts                  # Call alias to cd to $HOME$/Sys/Scripts   
~/Sys/Scripts$    
 

This works for us because we’ve spent a good bit of time organizing our account file structure and have some specific mnemonic names for our sub-folders. But our method assumes that:

- We know our account folder structure pretty well; 
- Our sub-directory names are mostly unique; 
- We’re willing to do some memorization.

We like the $HOME environmental variable within our aliases (instead of `/home/myaccount`) to increase alias robustness: The alias will work unchanged if we move the entire contents of our account to another with directories intact. That is, if we change our Linux account name. (**Off Topic:** This is a good idea once in a blue moon for security purposes.)

Of course there’s nothing preventing combing the two navigation speed-up techniques. They’re quite compatible.

Wrap-Up

This article has already become a master’s thesis on aliasing, so we conclude with a simple case study about how we solved a sticky command line problem in a simple way. To lead with the spoiler, we’ll call this example…

...The Little Alias That Could

Background: Julia is a somewhat recent, Open Source, programming language, oriented toward Mathematics, Data Science, and AI, that may eventually replace languages like MatLab, R, and perhaps even Python. Julia’s tag line when it first hit the streets was “writes like Python, runs like C” which gives the reader the flavor and is actually a pretty good six-word description.

We like programming in Julia much better than in bash. Julia reads as much like pseudo-code as any language we’ve ever encountered. Boatloads of examples here. Translating simpler Python programs into working Julia is often trivial substitution. In addition, Julia happens to be a very good general purpose language with a many nice file system functions built in.

We reasoned that Julia could be a great replacement for bash programming in almost any situation, especially complex file management work. Like transcoding .mp4 files in an extensive audio library.

Except for one thing…. Julia is not so great at paths. Actually “path-blind” might be more accurate.

The nice thing about a bash script, let’s call it mybscript, is that we can pick a folder to stash our bash script files in, for instance ~/Sys/Scripts, include that folder within the PATH variable set in our .bashrc file, then bounce around our directories and run our mybscript in whatever PC folder we find ourselves. We only have have to type the file name, mybscript, at the prompt. This is completely by design because bash is a file system shell, after all.

On the other hand, running a Julia script at an arbitrary folder location requires something like this:

plaintext   
julia ~/Sys/Scripts/myjscript.jl   
 

The system can find where the Julia interpreter resides easily enough, but we have to tell the interpreter exactly where the Julia script resides to run it within the interpreter. No search path here. That’s a lot of typing and a deal killer for something we want to be quick and easy at the command prompt like a bash script.

As the reader has likely guessed, aliases solve this dilemma neatly. The solution is to add an alias to .bashrc for each Julia script we write. So within .bashrc we might have the following alias to run myjscript:

plaintext   
alias myjscript="julia $HOME/Sys/Scripts/myjscript.jl"   
 

Unpacking this:

- myjscript is the alias name for the Julia script we can call from anywhere.   
- The alias string starts the julia interpreter which, when a script file name is passed to it at startup, runs the script as a one-off then returns to the bash shell prompt just like any other shell command. (Instead of starting interactive Julia at the command line.)   
- .jl, the standard Julia script file extension, is added to the file name in the alias string to save typing.   
- If the particular script needs extra arguments they can be appended to the alias at the command line when invoking the script like so:

plaintext   
~/Desktop$ myjscript arg1 arg2 ... argN   
 

We have some ideas for further improvements but this serves as an example of how aliases can solve a knotty shell problem. Bottom line is that we’ve enabled scripting in Julia that works exactly like bash programs that honor `PATH`.

And that’s it. Hopefully we’ve given the reader some aliases s/he can use for his daily Linux workflow as well as stimulated his thinking about other ways to employ aliases.

Bootnotes

Article content developed and tested on

- A System 76 Thelio desktop PC with 16GB of RAM and 256GB SSD.   
- MX Linux 21.3 with 5.18 kernel, Xfce 4.18.1, bash 5.14(1), and Julia 1.9.2.

 

 


 


 



 


 

Tags

Category

Comments