How to use Aliases in Linux to Shorten Long Commands

Tired of typing the same long commands each time you have to use them in Linux? Create aliases! An alias is an abbreviated command, a short word you choose that will do the work of a long command requiring switches or parameters.

Creating Aliases in Linux

First, install the vim text editor:

[code lang=”shell”]
sudo apt-get install –install-recommends –force-yes vim
[/code]

Then create the hidden file .bashrc in your home directory, and open it with vim:

[code lang=”shell”]
touch ~/.bashrc
vim ~/.bashrc
[/code]

If you have vim installed already, all you need is:

[code lang=”shell”]
vim ~/.bashrc
[/code]

The file will likely be empty initially:

Press the Insert key so you can write in vim’s window. Create your own aliases for the commands you use most often.

Alias creation follows the format: alias name=’command‘. For example, if you frequently use the command ls -alr (this lists all files in a directory, including hidden files, sorted in reverse order with long listings), you can use an alias like:

[code lang=”shell”]
alias ls=’ls -alr’
[/code]

Now whenever you type ls, it will actually issue ls -alr.

When you are done, press the Escape key (ESC) to exit Insert mode, then press the colon key (:) to access the input line, and type wq. The w tells vim to write the file, and q means quit.

Press enter to close vim, then exit and re-open the terminal.  The contents of .bashrc are read when the new terminal opens, and your aliases will now be available for use.

Sample Aliases

Use “up” to check for package updates with apt

[code lang=”shell”]
alias up=’sudo apt-get update’
[/code]

Use “upg” to apply available updates with apt

[code lang=”shell”]
alias upg=’sudo apt-get upgrade’
[/code]

Use “upup” to both update and upgrade available packages

[code lang=”shell”]
alias upup=’up && upg’
[/code]

Use “install” to install packages using apt

[code lang=”shell”]
alias install=’sudo apt-get install’
[/code]

Use “remove” to remove packages using apt

[code lang=”shell”]
alias remove=’sudo apt-get remove –purge’
[/code]

Use “autorm” to clean up package dependencies

[code lang=”shell”]
alias autorm=’sudo apt-get autoremove’
[/code]

Use “mplay” to run mplayer, with colored text, from the command line

[code lang=”shell”]
alias mplay=’mplayer -msgcolor’
[/code]

Use “rkhunt” to start Rootkit Hunter

[code lang=”shell”]
alias rkhunt=’sudo rkhunter -c –sk’
[/code]

Conclusion

Aliases are useful for so many commands that they cannot all be listed here. Bottom line: If you use certain commands on a regular basis, create aliases for them and save yourself some time.


Posted

in

,

by

Tags:

Comments

Leave a Reply