Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

alias command and shell aliases

News

BASH

Best Shell Books

Recommended Links Bash customization Bash and ksh93 Shell Prompts Customarization

Shell functions

Customizing Shell Dot Files: .profile, RC-file, and history

Examples of .bashrc files Horror Stories bash Tips and Tricks Unix History Humor Etc

Aliases are positional parameterless macros. They are recognized only as the first word of the command string. And they allow only simple substitution.  The shell maintains a list of aliases that may be set and unset with the `alias' and `unalias' built-in commands. 

Aliases don't allow for control flow, command-line arguments, or other features that makes the command line so useful. For any more or less complex case, shell functions are preferred over aliases.

Additionally, the rules surrounding alias expansion are tricky, enough so that the bash(1) man page recommends "To be safe, always put alias definitions on a separate line, and do not use alias[es] in compound commands."

To create aliases shell contain special built-in alias command. The syntax for the Korn shell and its derivatives like bash is: 

alias name="value"

For example we can create an alias for the alias command:

alias a="alias"

The Korn shell comes with a default set of predefined aliases.

autoload=typeset -fu
false=let Ř
functions=typeset -f
hash=alias -t -
history=fc -l
integer=typeset -i
nohup=nohup
r=fc -e -
stop=kill -STOP
suspend=kill -STOP $$
true=:
type=whence -v

To display the list of current aliases, type alias and press Return

As I mentioned above aliases are essentially simple positional parameterless macros. The first word of each command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The alias name and the replacement text may contain any valid shell input, including shell metacharacters, with the exception that the alias name may not contain `='. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias `ls' to `"ls -F"', for instance, and Bash does not try to recursively expand the replacement text. If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.

In ksh and bash there is no mechanism for using arguments in the replacement text, as in `csh'. If arguments are needed, a shell function should be used

Aliases are not expanded when the shell is not interactive, unless the `expand_aliases' shell option is set using `shopt' (*note Bash Builtins::).

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use `alias' in compound commands.

Warnings:

$ alias rm='rm -i'
$ cd ~/scratch
$ rm *  # here the rm alias catches you and interactively
     # deletes the contents of your current directory

and then later in the same session doing this:

$ su -
# cd /tmp
# rm # here the rm alias no longer exists, and you whack
   # a bunch of stuff out of /tmp

Good luck !

Dr. Nikolai Bezroukov


Heelo
Top Visited
Switchboard
Latest
Past week
Past month


NEWS CONTENTS

Old News

Linux.com CLI Magic Daily aliases

created and tested all of the following aliases on SUSE 10 with the bash shell.

List the most recently modified files and directories

alias lt='ls -alt | head -20'

Once it's loaded, typing lt lists the most recently modified contents of the current directory. The -a and -l options show all files including hidden files in a long listing format. Since I am usually interested in a file I have just changed, I limit the output to 20 lines by piping the output from ls -alt to the head command. This example also demonstrates that an alias may be a series of commands, rather than just a short name for a single utility and its options.

List only subdirectories

alias ld='ls -al -d * | egrep "^d"'

This alias shows only subdirectories of the current directory by using egrep to limit the listing to entries with the d (directory) attribute.

Show the inode number for files in the current directory

alias li='ls -ai1 | sort'

This alias prints the inode number for each file, sorted in ascending order. The last option to ls in this alias is the numeral one, not the letter L. You might need the inode number for file system repair, or to track down a file name referenced by inode in an Security Enhanced Linux (SELinux) log file.

Show the SELinux security context of all processes

alias pss='ps --context ax'

As the SELinux code starts to appear in mainstream distributions, the security context of processes is something you may need to track. This alias displays the security context of all processes. The --context option tells ps to display the security context, while the a and x options combine to select all processes.

Fast directory navigation with pushd and popd

alias +='pushd .'
alias _='popd'

I tend to move around a lot on the command line. If I am working on code in a deeply nested directory, but need to go check some log files, I'll use the shell built-in pushd command to save my current directory location and popd to get back to the directory later.

These aliases simplify the process by entering + before changing directories, and _ to return to the directory later. You can push more than one directory on to the stack and pop them back off in reverse order. Note that I used the underscore instead of the minus sign for popd because the minus sign is a reserved symbol.

Find disk space abusers

alias dusk='du -s -k -c * | sort -rn'

... ... ...

Show all programs connected or listening on a network port

alias nsl='netstat -alnp --protocol=inet | grep -v CLOSE_WAIT | cut -c-6,21-94 | tail +2'

... ... ...

Quickly find packages in the RPM database

alias rpmq='rpm -qa | grep $1'

Aliases and Variables Keep Things Short and Simple

In tcsh, this can be done straightforwardly using !:1 for the first argument, !:2 for the second, and so on. Remember, you'll need to escape the ! in the alias definition.

So for my LDAP search:

alias finduser 'ldapsearch "(localUser=!:1)"'
Then the following:
$ finduser username

Unfortunately, in bash/sh/ksh this is no good, as you can't put arguments in aliases. What you can do to produce the same effect is write a function.

function finduser() { ldapsearch "(localUser=$1)"; }
(Note the ; at the end of the command.)

Jamie's Shell Stuff

alias cls=clear
 
alias hist=history
alias !='history | tail -15'
 
alias l='ls -alF'
alias ll='ls -alF'
alias dir='ls -la'
alias la='ls -Fa'
 
alias md='mkdir -p'
alias rd=rmdir
alias ..='cd ..'
alias ...='cd ../..'
alias +='pushd .' 

[X-Unix] Quoting in bash aliases

Eugene Lee list-themacintoshguy at fsck.net
Thu Feb 19 04:47:35 PST 2004

On Thu, Feb 19, 2004 at 01:28:32PM +0100, Kirk McElhearn wrote:
: 
: The following command replaces Mac line breaks with Unix line breaks:
: 
: perl -pi -e 's/\r\n?/\n/g'
: 
: I'd like to make an alias in bash, something like:
: 
: alias rplc='perl -pi -e 's/\r\n?/\n/g''
: 
: But the above doesn't work. I assume it has something to do with quoting.
: I've tried double-quotes, escaping the quotes in the perl string and more.
: 
: Can anyone tell me how this needs to be quoted to work correctly?

This worked for me at the command line:

	$ alias rplc="perl -pi -e 's/\r\n?/\n/g'"

Once the alias was created, this is how /bin/bash stored it:

	$ alias
	alias rplc='perl -pi -e '\''s/\r\n?/\n/g'\'''

However, you can use the rules of quoting to create an alias that is
easier to type and easier to read:

	$ alias rplc='perl -pi -e "s/\r\n?/\n/g"'


-- 
Eugene Lee
http://www.coxar.pwp.blueyonder.co.uk/

Useful Bash Aliases and Other Stuff

I'm not much into aliases, but here is what I got:

alias L='ls -FLb'
alias LL='ls -FLlb'
alias a='alias'
alias h='history'
alias j='jobs -l'
alias l='ls -Fb'
alias la='ls -Flab'
alias ll='ls -Flb'
alias m='less'
alias ot='popd'
alias to='pushd'
alias zm='zless'

Basically a bunch of ls shorthands (short listing, long listing, long with hidden files, short and long following symlinks).

OneOfOne - Tips-Bash Aliases

alias cp="cp -ia"
alias mv="mv -i"
alias rm="rm -i"
alias ls="ls --color=auto -h"
alias lss="ls --color=auto -hA"
alias l="ls --color=auto -hl"
alias cd..="cd .."
alias df="df -hT"
alias emerge="emerge -v"
alias unmerge="emerge unmerge"
alias untbz2="tar -xjvf"
alias untgz="tar -xzvf"
alias unbz2="bunzip2 -k"
alias grepi="grep --color=auto -Hirn"
alias psf="ps -ef"
alias psx="ps aux"
alias killwine="killall -9 wine; killall -9 wineserver"
alias netstati="netstat --verbose --tcp --udp --programs --extend"
alias mount_ro="mount -o ro,remount"
alias mount_rw="mount -o rw,remount"
alias clearswap="swapoff -a && swapon -a"
alias ka="killall -9"
alias free="free -m"
alias synctime="rdate -s ntp0.cornell.edu"
alias df="df -h"

bash.aliases [Homepage von Robert Kehl]

alias md=mkdir
alias rd=rmdir
alias su-='sudo su -'

# inventions

alias ghist='history | grep '
alias lf='find -type f | sort '
alias load='cat /proc/loadavg '
alias meminfo='cat /proc/meminfo '
# logs
alias mylogs='sudo tail -f /var/log/{apache2/*log,squid/access.log,otrs.log,exim*log,messages}'
alias mylogs2='sudo tail -f /var/log/{syslog,daemon.log,user.log,router.log}'
# OTRS
alias vio='vi /opt/otrs/Kernel/{Config/Defaults.pm,Config.pm}'

# Kalendar
alias kal='clear;echo -n "Heutiges Datum: ";date;echo;cal -3m'

# switch off
alias s &>/dev/null && unalias s
alias p &>/dev/null && unalias p

Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

Advanced Bash-Scripting Guide - Chapter 24. Aliases

Files, Users, and Shell Customization

Shell Aliases

An alias is a short form of a command. The built-in alias command creates simple abbreviations for the current Bash session.

To create an alias, use the alias command to assign a command and its switches a name.

$ alias lf='ls -qFl'
$ lf
-rw-r-----  1 kburtch  devgroup   10809 Apr 6 11:00 assets.txt
-rw-r-----  1 kburtch  devgroup   4713 Mar 9 2000 mailing_list.txt

Typing the alias command by itself, or with the -p switch, lists the current aliases.

$ alias
alias lf='ls -qFl'

Bash interprets an alias only once, allowing the aliasing of a command with its own name.

$ alias ls='ls -qF' # Bash isn't confused

Normally, only the first word of a command is checked for an alias. As a special exception, if the last character in the alias string is a blank, Bash checks the next word in the command to see whether it is also an alias.

There is no method for giving arguments to an alias. If arguments are needed, define a more powerful shell function instead.

The built-in unalias command removes an alias. Use the -a switch to remove them all.

Most Linux distributions have aliases defined for common commands. dir, for example, is often an alias for ls. Some distributions define an alias for commands such as rm -i to force user prompting, which is not required by default. This can be a problem for some users such as experienced Unix programmers who are used to working with these features disabled. Use unalias to remove any aliases that you don't want to use.

Aliases mixed with shell functions can be confusing because aliases are expanded only when a line from a script is read. If aliases are used in a shell function, they are expanded when the shell function is defined, not when it is executed. For this reason, it is safer to avoid aliases altogether in shell scripts. However, they can be turned on in scripts using the shopt –s expand_aliases command.

Functions and aliases in bash LG #53

The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands.

The first word of each command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The alias name and the replacement text may contain any valid shell input, including shell metacharacters, with the exception that the alias name may not contain =. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.

Aliases are created and listed with the alias command, and removed with the unalias command.

There is no mechanism for using arguments in the replacement text, as in csh. If arguments are needed, a shell function should be used (see section Shell Functions).

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see section Bash Builtin Commands).

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when the function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

Note that for almost every purpose, aliases are superseded by shell functions.

Alias Builtins

alias
alias [-p] [name[=value] ...]

Without arguments or with the `-p' option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, the name and value of the alias is printed.

unalias
unalias [-a] [name ... ]

Remove each name from the list of aliases. If `-a' is supplied, all aliases are removed.


Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: July 13, 2017