How to Create Aliases and Shell Functions on Linux?

Knowing the command prompts & shell scripts is still necessary if you want to get the most out of the GNU/Linux system & the more one operates at the command line, the more one will find that the majority of the commands being used are a very small subset of the available commands. Most tasks are habitual & the user you may run these the same way every day.

Linux System

While the makers of many of the most common command utilities have attempted to eliminate extraneous typing by using shortened names e.g. instead of list we type “ls” & instead of change-directory we type “cd”. Additionally, many Linux users often need to use one command over and over again. Typing/copying the same command again & again will reduce productivity & distracts the user from actual work.

It would be great if we spend less time typing those long commands. We have Two powerful ways to minimize your time at the command line are shell aliases and functions, by the use of these two, user can Tame repetitive tasks, shorten lengthy processes, & configure customized commands with the options the user always uses & struggle to remember.

You can define your commands suited to your specific needs, and to ease the burden of repetitive tasks.

Aliases and shell scripts i.e. functions do the same sort of job. They allow you to define—and name—a set of Bash shell functionality that is then callable by the name you’ve given to it. Typing the name is easier and more convenient than having to type out all of the steps or commands each time you want to use them.

The difference between an alias and a function is one of complexity & scale. Scripts are better at holding longer and more elaborate chunks of code. Aliases are perfect for holding shorter, more succinct, sets of commands.

Shell Aliases

A shell alias is a custom shortcut to reference a command or set of commands executed with or without custom options. These aliases are alternative, easy-to-remember names for long commands that you need to execute frequently. When you type at the command line, the shell first looks for what you wrote in its list of aliases. If a match is found, that would be replaced by the alias with its corresponding text; after completing that, it would again look at the whole resulting command line & executes it.

Chances are you may already have used the aliases on the Linux system as most Linux distributions add at least some of the popular aliases by the default in “.bashrc” file of the user account.

Beyond aliases: Shell functions

Blocks of similar but not identical codes cannot be replaced by Aliases. They cannot handle errors nor return custom exit codes, do flow control, or use variables. If you need to do any of these, it’s time to use shell functions.

Shell functions are code blocks structured as complete sub-scripts, written once and invoked from any script that needs it.

Syntax of aliases:

Creating aliases in bash is very straight forward. The syntax is as follows:

alias alias_name=”command_to_run”

To create a new bash alias in the current session

  1. Type the “alias
  2. Then declare the alias name
  3. Followed by an equal sign
  4. And the command that will run when the alias is called.

The command must be enclosed in quotes & with no spacing around the equal sign. Spaces here will break the command. Each alias must be declared on a new line.

Let us get it clarified by the example. On the Linux command line, one of the most used command is “ls”. Mostly “ls” command is used with the “la” switch which will list out all files & directories with hidden files in the format of the long list. Now we will create a simple bash alias “ll” which will be a shortcut to the ls -la command.

  1. Open a terminal window
  2. Type:
    alias ll="ls -la"

    & press enter

    Alias ll
  3. Now in the console type “ll” and press enter
    Run of Alias ll
  4. The output will be the same as by typing ls -la.

The above-defined alias “ll’ will only be available in the current shell session. If you close the session or a new session window initiated from another terminal the above-defined alias “ll” will not be available.

Alias command ll not found out of session

We will discuss it later on how to make the alias persistent. The examples here are for the bash shell, but all the concepts and most of the code are valid for other shells too.

Predefined Aliases

Some aliases are predefined for you. To know the list of all aliases that are defined in the system, we will use the “alias” command without any parameters:

alias

These are the aliases on the Ubuntu test machine this article was researched on. Also, any custom-defined aliases, would show up in this list too.

There’s a bunch of different aliases for the ls command, and there’s a group of aliases that provide color output to the grep family of commands e.g. with aliases defined as above, whenever you type:

grep

It will be interpreted as:

grep --color=auto

This shows an important point with aliases. They can have the same name as existing commands.  They can even contain the original command within themselves.

Here is the definition of the grep alias.

alias grep='grep --color=auto'
  1. The alias command is used to define an alias.
  2. The name of the alias is given next. In this example, it is “grep”.
  3. The equals sign connects the name of the alias to the body of the alias. For all but very simple aliases, the body of the alias is enclosed within single quote marks ‘.
  4. The body of the alias is the section that is executed when the alias is used on the command line.
  5. The body of this alias simply calls the grep command with the –color=auto option.

The Alert Alias

At the top of the listing, there’s a complicated-looking alias called alert. As a quick aside, and so that you know what it does, the alert alias is used to let you know when a command has finished. It also indicates whether the command completed successfully or not. It provides a graphical system alert at the top of the screen.

Here’s a simple example. The sleep command will sleep for five seconds., The alert alias will then be called. The alias checks the response from the previous command. It extracts the last command from the history file. It determines whether the command completed successfully or not. It then presents the results in a system alert.

If the command completed as expected, the icon in the system alert is a small terminal window. If the command returned an error code, the icon in the system alert is a red error icon.

sleep 5; alert
Alert for sleep

After five seconds, we see this system alert:

Output of Alert sleep

The icon is a small terminal window, meaning everything went well. Let’s try that again with a command that we know will fail:

DoomedToFail; alert
Alert for fail

Our system alert now has an error icon.

Output of fail alert

Defining a Trivial Alias

As we’ve seen, to define an alias, we use the alias command.

We’re going to create a pseudonym for the clear command. Our alias will be called cls and it will call the clear command.

Our alias definition is so trivial that it doesn’t warrant being wrapped in single quote marks. If the body of the alias is any more complex than this, or if it contains spaces, wrap it in single quotes. We’ll define the alias, use ls to put some output in the terminal window and then use our new alias cls to clear the screen.

alias cls=clear

ls -l

cls
Alias cls

The screen is cleared. Success, albeit shortlived. The alias will survive only as long as this terminal window remains open. Once the window is closed, the alias will vanish.

To make Aliases permanent by use of The “.bashrc” File

You might be wondering where the pre-packaged aliases are defined. it is in the “.bashrc” file in your home folder. This file is read, and the commands inside it executed whenever you start an interactive shell. That is when you open a terminal window.

Type the following command in your home folder to see the contents of the “.bashrc” file with syntax highlighting.

gedit .bashrc
Edit of .bashrc

This will launch the gedit editor with the “.bashrc” file loaded into it.

.bashrc file contents showing alias

The highlighted areas show two areas where aliases are defined.

Scrolling through the document will reveal two other sections related to aliases:

if statement of .bash_alias in .bashrc file

The first of these is the definition of the alert alias. The second is an if statement. It translates to, “if the file “.bash_aliases” exists, read it in.”

If you only have a few aliases that you wish to define, you might put them in your “.bashrc” file. Tuck them in below the section containing the ls aliases.

If you are going to create a lot of aliases, or you just like the idea of having your aliases encapsulated within the own file, you can define them in your “.bash_aliases” file. One advantage of creating them in your “.bash_aliases” file is you can’t accidentally change any of the settings in the “.bashrc” file. Another advantage is your aliases are easily copied to new systems because they are separated from the “.bashrc” file.

The alias should be named in a way that is easy to remember. It is also recommended to add a comment for future reference.

Storing Aliases in the .bash_aliases File

The “.bash_aliases” file does not exist by default, you will have to create it. You can create the file with this command:

touch .bash_aliases
creating bash_aliases file

Let’s edit the file and add a few aliases to it. This command will open the “.bash_aliases” file in the gedit editor.

gedit .bash_aliases
Defining Alias in .bash_aliases file

We’ve added three aliases. The first is our cls alias which we used earlier. The next is called h. and is a shorthand way of calling the history command.

The third alias is called ftc. This stands for “file type count.”

This alias is more involved, so it is wrapped in single quote marks. It uses a chain of commands linked together by pipes. It produces a sorted list of the different file extensions and directory names, with a count for each list entry.

When we have saved the “.bash_aliases” file, we might expect our aliases to be live and accessible. That’s not the case. The file has to be read in by the Bash shell before the alias definitions are live. This is done whenever an interactive shell is opened.

We can also use the Bash shell built-in . to read and execute the commands in a file. Because our “.bash_alias” file is read in when “.bashrc” is processed, we ought to perform our test by calling “.bashrc”. That way we can check that the “.bash_alias” file is called from “.bashrc” and that our aliases are alive and well.

The commands we’ve used are:

gedit .bash_aliases

To edit the “.bash_aliases” file.

. .bashrc

This will read in and execute the commands within “.bashrc”, which will call “.bash_aliases”.

ftc

This will call the ftc alias.

Alias ftc

Our alias responds which means Bash has read in both “.bashrc” and“.bash_aliases”, and our new aliases are now live.

You can now go ahead and add new aliases to the “.bash_aliases” file as they occur to you. If you find yourself doing things more than once or twice, consider making an alias for it.

Removing Aliases

There is a command to remove aliases so that Bash doesn’t recognize them nor respond to them. Refreshingly forthright, the command is called unalias.

To use it, give the name of the alias you wish to have Bash forget. To make Bash forget our ftc alias, use unalias e.g. the previously used “ll” command:

unalias ll
Command unalias

You can use unalias to remove aliases you have defined and any of the predefined aliases.

To remove all of the aliases from your system, use the -a (all) option:

unalias -a

Bash’s loss of memory will not be permanent, though. The next time you open a terminal window, the “forgotten” aliases will be back. To truly wipe them out you need to remove them from your “.bashrc” and “.bash_alias” files.

If you think you’d ever like to have them back, don’t delete them from your “.bashrc” file. Instead, comment them out by adding a hash # to the start of each alias line. To make your “.bash_alias” file ineffective, rename it. If your “.bashrc” file can’t see it, it won’t read it in. Reversing these steps to reinstate your aliases is a trivial matter.

To temporarily bypass an alias (say we aliased ls to ls -a), we can type:

\ls

Resultantly the normal command would be called, not the aliased version.

Temporary alias removal

Help for Alias command:

  • –help option: It displays help Information.

Syntax:

alias --help
Alias help

Shell Functions

Sometimes an alias that could accept one or more arguments is required, that is when bash functions are used.

Syntax

Creating a bash function is not very difficult. They can be declared in any one of following two different formats:

function_name () {

  [commands]

}

or

function function_name {

  [commands]

}

We can compress this second form into one line and separate the commands with semicolons. A semicolon must come after the last command too:

function_name () { command1; command2; }

Lika aliases, Bash shell functions can be defined within the “.bashrc” file, but it is often neater to put them in their own definitions file. We’ll call it “.bash_functions”, following the convention used for the “.bash_aliases” file.

That means we need to tell the “.bashrc” file to read in our definitions. We can copy and amend the snippet of code that reads in the “.bash_aliases” file. Launch gedit and load the “.bashrc” file with this command:

gedit .bashrc
gedit .bashrc file

You need to add the highlighted section shown below.

You can highlight the alias section and press Ctrl+C and then move to where you’d like the new section and press Ctrl+V to paste a copy of the text. Then all you need to do is change the two places where it says “.bash_aliases” to “.bash_functions.”

Adding bash_functions in .bashrc file

We can save those changes and close gedit.

Now we are going to create and edit the “.bash_functions” file, and put a function definition in it.

touch .bash_functions

gedit .bash_functions
Creating and editing .bash_functions

This will open the empty “.bash_functions” file in gedit.

We’re going to add a simple function called up. up will take a single command line parameter, which is a digit. up will then call cd .. that number of times. So, if you used the command

up 2

up would call cd .. twice and would move up two levels in the directory tree.

There are different ways to define a function. Here’s one:

function up() {

The word function is optional. If you’re a traditionalist, use it, if you can’t be bothered typing it in, leave it out.

Here’s our entire function in gedit:

Editing .bash_functions file
function up() {

This marks the start of our function definition, and it names the function up.

levels=$1

This creates a variable called levels and sets it to the value of the first parameter. This parameter is going to be a digit provided by the user when they call the function. The $1 means “first command line parameter.”

while [ "$levels" -gt "0" ]; do

We then enter a loop which will then translate as “when the “value” of “levels” is positive or greater than zero, do what is contained in the body of the loop.”

Inside the body of the loop, we have two commands. They are:

cd ..

Move up a level in the directory tree.

levels=$(($levels - 1))

Set levels to a new value, which is one less than its current value.

We then go back to the top of the loop, the comparison between the value of levels and zero is made once more. If “levels” is more than zero, the body of the loop is executed again. If it is not positive or greater than zero, the loop is finished, & we drop through to the done statement, and the function is over.

Save these changes and close gedit.

We’ll read in and execute the commands in “.bashrc” which should read in and execute the commands in our “.bash_functions” file.

. .bashrc
Call ..bashrc

We can test the function by moving to some location in the directory tree and using up to move back to a “higher” point in the directory tree.

cd ./work/backup/

up 2
Function up

The function works. We’re moved two directory levels higher in the tree.

Keeping Track With type

As you build up a suite of aliases and a library of functions, it can become difficult to remember whether a particular command is an alias or a function. You can use the “type” command to remind you. The cool thing here is that you also get to see the definition.

Let’s use type on our ftc alias and our up function.

type ftc

type up
Use of type

We get a very useful reminder of what type of command each one is, together with their definitions.

Start Collecting

Aliases and functions can speed up your use of the command line tremendously. They can shorten command sequences, and they let you bake-in the options you always use with standard commands. Each time you see a nifty one-liner or useful function, you can adapt and personalize it, and then add it to your “.bash_aliases” or “.bash_functions” files. Extensive use of these can help make your time in the shell more enjoyable and less complex.

Remember to be wary of redefining existing commands with behavior that is potentially destructive. Even doing the opposite and aliasing a command to a safer variant (always asking for confirmation before deleting recursively, for instance) can come back to bite you the first time you’re on a system without it once you’ve come to rely on it. To find candidates that might be good to create aliases for, it might be a good idea to search your history for your most commonly used commands.

ABOUT THE AUTHOR

Kevin Arrows


Kevin Arrows is a highly experienced and knowledgeable technology specialist with over a decade of industry experience. He holds a Microsoft Certified Technology Specialist (MCTS) certification and has a deep passion for staying up-to-date on the latest tech developments. Kevin has written extensively on a wide range of tech-related topics, showcasing his expertise and knowledge in areas such as software development, cybersecurity, and cloud computing. His contributions to the tech field have been widely recognized and respected by his peers, and he is highly regarded for his ability to explain complex technical concepts in a clear and concise manner.