27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 24. Aliases<br />

A Bash alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding<br />

typing a long command sequence. If, for example, we include alias lm="ls −l | more" in the ~/.bashrc<br />

file, then each lm typed at the command line will automatically be replaced by a ls −l | more. This can save a<br />

great deal of typing at the command line and avoid having to remember complex combinations of commands<br />

and options. Setting alias rm="rm −i" (interactive mode delete) may save a good deal of grief, since it can<br />

prevent inadvertently losing important files.<br />

In a script, aliases have very limited usefulness. It would be quite nice if aliases could assume some of the<br />

functionality of the C preprocessor, such as macro expansion, but unfortunately Bash does not expand<br />

arguments within the alias body. [55] Moreover, a script fails to expand an alias itself within "compound<br />

constructs", such as if/then statements, loops, and functions. An added limitation is that an alias will not<br />

expand recursively. Almost invariably, whatever we would like an alias to do could be accomplished much<br />

more effectively with a function.<br />

Example 24−1. Aliases within a script<br />

#!/bin/bash<br />

# Invoke with command line parameter to exercise last section of this script.<br />

shopt −s expand_aliases<br />

# Must set this option, else script will not expand aliases.<br />

# First, some fun.<br />

alias Jesse_James='echo "\"Alias Jesse James\" was a 1959 comedy starring Bob Hope."'<br />

Jesse_James<br />

echo; echo; echo;<br />

alias ll="ls −l"<br />

# May use either single (') or double (") quotes to define an alias.<br />

echo "Trying aliased \"ll\":"<br />

ll /usr/X11R6/bin/mk* #* Alias works.<br />

echo<br />

directory=/usr/X11R6/bin/<br />

prefix=mk* # See if wild−card causes problems.<br />

echo "Variables \"directory\" + \"prefix\" = $directory$prefix"<br />

echo<br />

alias lll="ls −l $directory$prefix"<br />

echo "Trying aliased \"lll\":"<br />

lll<br />

# Long listing of all files in /usr/X11R6/bin stating with mk.<br />

# Alias handles concatenated variables, including wild−card o.k.<br />

TRUE=1<br />

Chapter 24. Aliases 286

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!