[Linux] Improve your CLI experience: define alias and function

You are here:
  • Main
  • Linux
  • [Linux] Improve your CLI experience: define alias and function
< All Topics

Hello everybody,

today we’re going to talk about something really useful in CLI: alias and function.


Aliases are a combination of commands that can’t manipulate any input.

Suppose that usually you need to install software via CLI, and always you’ve to prompt something like:

$ sudo apt install telnet

As you can see, you need to type a lot of characters.

You can quicken this tasks, just by adding an alias to your bash profile:

$ vi ~/.bashrc
alias inst_new='sudo apt install '

Now you can install telnet just typing:

$ inst_new telnet

Obviously, you can define really arbitrary complex aliases, for example if you need to stop all docker containers:

$ vi ~/.bashrc
alias st_ru_dock="docker ps | awk '{print \$1}' | grep -v CONTA | xargs docker stop"

As you can see, just typing:

$ st_ru_dock

This will be the state of the system:

Aliases are really useful and powerful for every user, from the novice to sysadmin, and creating them could really help you during the day.


Functions are more powerful command, that let’s you do some complex stuff.

For example, suppose that you usually write scripts in your command line, but you want always backup them before modifying them. So, everytime you need something like this:

$ cp my_scripts my_script.old

But everytime you’ve to modify the name to my_script.old.1, my_script.old.2, etc..

Now, you can define a simple function that, given as input a file, will create a copy with a date in the name.

$ vi ~/.bashrc
function backup_file(){
 cp -p $1 $1.$(date +%d%m%y_%H%M)

In this way, you just need to do this for creating a backup of your file:

$ backup_file myscript

As you can see, you will have a copy of you file with date, so you always know which one is the latest before the actual one.

Moreover, you can implement a function that has a lot of lines of code, to improve your daily job, for example, if you’ve to find where are the log of your Oracle Database:

$ vi ~/.bashrc 
function log(){
alert=$(sqlplus -s / as sysdba <<EOF
set heading off
select inst_id,name,value from v\$diag_info where name = 'Diag Trace';
ls $(echo $alert | tail -1 | awk '{print $NF}')/alert*.log

That’s it, now you can define your aliases and functions to improve you life with the CLI.


Table of Contents