How to create aliases and shell functions in Linux

Contents

A terminal window on a Linux laptop

Create your own Linux commands using aliases and bash shell functions. Control repetitive tasks, truncate lengthy processes and configure standard commands with alternatives you always use and have a hard time remembering.

Alias and shell scripts are powerful techniques on Linux and Unix-like operating systems that allow you to hone your command line experience to be exactly what you want. You can set your own commands tailored to your specific needs and to ease the burden of repetitive tasks.

Aliases and scripts de shell do the same kind of work. They enable you to establish (and name) a set of bash shell functions that can then be called by whatever name you have given. Typing the name is easier and more convenient than having to type all the steps or commands every time you want to use them.

The difference between an alias and a script is one of complexity and scale. Scripts are better for saving longer and more elaborate code snippets. Aliases are perfect for keeping command sets shorter and more concise.

Predefined aliases

Some aliases are predefined for you. To see the list of aliases that are defined on your system, use alias command without parameters:

alias

These are the aliases that are defined on the Ubuntu test machine this post was investigated on. If I had defined any custom aliases, these would also appear in this list.

At the top of the list, there is a tricky looking alias called alert. We'll get to that in a moment. There are a lot of different aliases for ls command, and there is a group of aliases that provide color output to the grep command family. As an example, with these aliases defined, whenever I write:

grep

The system will interpret it 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 grep alias.

alias grep = 'grep --color = auto'
  • the alias The command is used to set an alias.
  • The name of the alias is given below. In this example it is grep.
  • The equal sign connects the Name from alias to body alias. For all aliases, except the very simple ones, the body of the alias is enclosed in single quotes '.
  • The body of the alias is the section that is executed when the alias is used on the command line.

The body of this alias simply calls the grep command with the --color=auto option.

Alias ​​alert

As a brief aside, and so you know what it does, the alert alias is used to notify you when a command has finished. It also indicates if the command completed successfully or not. Provides a graphical system alert at the top of the screen.

Here is a simple example. the sleep The command will sleep for five seconds. alert then it will be called alias. The alias verifies the solution of the above command. Extract the last command from the archive file. Determines whether the command completed successfully or not. Then present the results in a system alert.

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

sleep 5; alert

After five seconds, we see this system alert:

System alert for suspend command

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

DoomedToFail; alert

Our system alert now has an error icon.

Definition of a trivial alias

As we have seen, to set an alias, we use the alias command.

Let's create a pseudonym for him clear command. Our alias will be called cls and will call clear command.

Our definition of aliases is so trivial that it doesn't justify being in single quotes. If the alias body is more complex than this, or if it contains spaces, wrap it in single quotes. We will define the alias, use ls to put some output in the terminal window and then use our new alias cls to clean the screen.

alias cls=clear
ls -l
cls

Screen clears. Success, even when short-lived. The alias will survive only as long as this terminal window remains open. Once the window is closed, the alias will disappear.

Then, How do we make our aliases permanent??

The .bashrc file and aliases

You may be wondering where prepackaged aliases are defined. is in the archive “.bashrc” in your home folder. this file is read and the commands it contains are executed each time you start an interactive shell. In other words, when you open a terminal window.

type the following command in your home folder to view the contents of the file “.bashrc” with syntax highlighted.

gedit .bashrc

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

gedit with .bashrc loaded on it

Highlighted areas show two areas where aliases are defined.

When you scroll through the document, two other sections associated with aliases will be revealed:

The first of these is the definition of alert alias. The second is a if statement. It translates as, “whether the file” .bash_aliases “exists, Read”.

If you only have a few aliases that you want to set, you can put them in your ".bashrc" file. Place them below the section that contains the ls alias.

If you are creating many aliases, or you just like the idea of having your aliases encapsulated within your own file, you can define them in your ".bash_aliases" file. An advantage of creating them in your file “.bash_aliases” is that you cannot accidentally change any of the settings in the file “.bashrc”. Another advantage is that their aliases are easily copied to new systems because they are totally divorced from the ".bashrc" file..

Storing aliases in the .bash_aliases file

The file “.bash_aliases” it won't exist until you believe it. you can create the file with this command:

touch .bash_aliases

Let's edit the file and add some aliases. This command will open the file “.bash_aliases” at gedit editor.

gedit .bash_aliases

We've added three aliases. The first is our cls aliases we previously used. The next one is called h. and is a shorthand way to call history command.

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

This alias is more complex, so it is included in single quotation marks. Uses a string of commands joined together by pipes. Produces an ordered list of the different file extensions and directory names, with a count for each entry in the list.

RELATED: How to use Pipes on Linux

When we have saved the file “.bash_aliases”, we could expect our aliases to be active and accessible. That's not the case.. the bash shell must read the file before alias definitions are active. this is done whenever an interactive shell is opened.

We can also use the integrated Bash shell. . for read and execute commands in a file. Because our archive “.bash_alias” reads when processed “.bashrc”, we must perform our test by calling “.bashrc”. That way we can check that the file ".bash_alias" is called from ".bashrc" and that our aliases are alive and in good condition.

The commands we use are:

gedit .bash_alias

To edit the file “.bash_alias”.

. .bashrc

This will read and execute the commands within “.bashrc”, who will call “.bash_alias”.

Ftc

This will call the ftc alias.

Our alias responds, which means Bash has read so much in “.bashrc” like in “.bash_aliases”, and our new aliases are now active.

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

Delete aliases

There is a command to remove aliases so that BAsh does not recognize or respond to them. Refreshingly frank, the command is called unalias.

To use it, give the name of the alias you want Bash to forget. To make bash forget our ftc alias, use unalias like this:

unalias ftc

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

To remove all aliases from your system, Use the -a (everything) option:

unalias -a

Despite this, Bash memory leak will not be permanent. The next time I open a terminal window, aliases “Forgotten” Will. To really remove them, you must delete them from your files “.bashrc” and “.bash_alias”.

If you think you'd ever like to get them back, do not delete them from your ".bashrc" file. Instead, comment on them by adding a hash # at the beginning of each alias line. So that your ".bash_alias" file is not effective, rename it. If your ".bashrc" file can't see it, will not read it. Reversing these steps to reset your aliases is a trivial matter..

Shell Features

Lika's aliases, Bash shell functions can be set within the ".bashrc" file, but it's often best to put them in your own definition file. you will need to start by enabling the developer tab by clicking on the dropdown menu “.bash_functions”, following the convention used for the file “.bash_aliases”.

That means we should tell the ".bashrc" file to read our definitions.. We can copy and modify the code snippet that is read in the file “.bash_aliases”. Launching gedit and upload the file “.bashrc” with this command:

gedit .bashrc

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 want the new section and press Ctrl+V to paste a copy of the text. After, all you need to do is change the two places where it says “.bash_aliases” a “.bash_functions”.

We can save those changes and close gedit.

Now let's create and edit the ".bash_functions" file and put a function definition in it.

touch .bash_functions
gedit .bash_functions

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

Let's add a simple function called up. up will take a single command line parameter, what is a digit. up then i will call cd .. that many times. Then, if you used the command

up 2

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

There are different alternatives to set a function. Here's one:

function up() {

The word function it's optional. If you are a traditionalist, use it, if you don't bother to write it, leave it out.

Here is our entire function in gedit:

The shell up function () Bash and gedit

function up() {

This marks the beginning of our function definition, and name the function up.

levels=$1

This creates a variable called levels and set it to the value of the first parameter. This parameter will be a digit provided by the user when calling the function. the $1 it means “first command-line parameter”.

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

Then we go into a loop. This translates as “while the value of levels is greater than zero, do what is contained in the loop body “.

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

cd ..

Go up one level in the directory tree.

levels=$(($levels - 1))

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

Then we return to the top of the cycle, the comparison between the value of levels and becomes zero. And levels is greater than zero, the loop body is rerun. If not greater than zero, the loop ends and we go to done statement, and the function is over.

save these changes and close gedit.

We will read and execute the commands in “.bashrc” that should read and execute the commands in our file “.bash_functions”.

. .bashrc

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

cd ./work/backup/
up 2

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

Keep track with the guy

As you create a set of aliases and a library of functions, it can be difficult to remember if a particular command is an alias or a function. You can use the type command to remember you. The good thing here is that you can also see the definition.

Let's use type in our ftc alias and our up function.

type ftc
type up

We get a very useful reminder of what kind of command each is, along with their definitions.

Start collecting

Aliases and functions can greatly speed up the use of the command line. They can shorten scripts and allow you to incorporate the alternatives you always use with standard commands.

Whenever you see a nifty or useful feature, you can adapt and customize it, and then add it to your ".bash_aliases" or ".bash_functions" files.

setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq = n;n.push=n;n.loaded=!0;n.version=’2.0′;
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s) } (window, document,’script’,
‘https://connect.facebook.net/en_US/fbevents.js’);
fbq(‘init’, ‘335401813750447’);
fbq(‘track’, ‘PageView’);
},3000);

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.