|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
Softpanorama Search
|
| Recommended Links | Shell functions |
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:
Aliases are very useful things, but I hope that you will find functions at least as interesting and even more useful. You should be very careful replacing a standard command with an alias or a function.
It's too easy to really hurt yourself by trying to execute your alias when it doesn't exist. Imagine the difference between doing this:
$ alias rm='rm -i' $ cd ~/scratch $ rm * # here the rm alias catches you and interactively # deletes the contents of your current directoryand 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
|
|||||||
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
ltlists the most recently modified contents of the current directory. The-aand-loptions 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 fromls -altto theheadcommand. 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
--contextoption tellspsto display the security context, while theaandxoptions 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'
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:
Then the following:
alias finduser 'ldapsearch "(localUser=!:1)"'
$ 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.
(Note the ; at the end of the command.)
function finduser() { ldapsearch "(localUser=$1)"; }
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 .'
Eugene Lee list-themacintoshguy at fsck.net
Thu Feb 19 04:47:35 PST 2004
- Previous message: Quoting in bash aliases
- Next message: [X-Unix] Quoting in bash aliases
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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/
|
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"
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
Advanced Bash-Scripting Guide - Chapter 24. Aliases
Files, Users, and Shell Customization
Shell AliasesAn 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.txtTyping 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 confusedNormally, 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.
The shell maintains a list of aliases that may be set and unset with the
aliasandunaliasbuiltin 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
lsto"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
aliascommand, and removed with theunaliascommand.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_aliasesshell option is set usingshopt(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
aliasin 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,
aliasprints 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.
Copyright © 1996-2009 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. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
Last modified: August 08, 2009