Baixe abs (advenced bash script) -guide e outras Notas de estudo em PDF para Física, somente na Docsity!
An in-depth exploration of the art of shell scripting
Mendel Cooper
10 Mar 2014
Revision History
Revision 6.5 05 Apr 2012 Revised by: mc
'TUNGSTENBERRY' release
Revision 6.6 27 Nov 2012 Revised by: mc
'YTTERBIUMBERRY' release
Revision 10 10 Mar 2014 Revised by: mc
'PUBLICDOMAIN' release
This tutorial assumes no previous knowledge of scripting or programming, yet progresses rapidly toward an
intermediate/advanced level of instruction... all the while sneaking in little nuggets of UNIX® wisdom and
lore. It serves as a textbook, a manual for self-study, and as a reference and source of knowledge on shell
scripting techniques. The exercises and heavily-commented examples invite active reader participation, under
the premise that the only way to really learn scripting is to write scripts.
This book is suitable for classroom use as a general introduction to programming concepts.
This document is herewith granted to the Public Domain. No copyright!
Dedication
For Anita, the source of all the magic
Table of Contents
Table of Contents
Chapter 1. Shell Programming!
No programming language is perfect. There is
not even a single best language; there are only
languages well suited or perhaps poorly suited
for particular purposes.
--Herbert Mayer
A working knowledge of shell scripting is essential to anyone wishing to become reasonably proficient at
system administration, even if they do not anticipate ever having to actually write a script. Consider that as a
Linux machine boots up, it executes the shell scripts in /etc/rc.d to restore the system configuration and
set up services. A detailed understanding of these startup scripts is important for analyzing the behavior of a
system, and possibly modifying it.
The craft of scripting is not hard to master, since scripts can be built in bite-sized sections and there is only a
fairly small set of shell-specific operators and options [1] to learn. The syntax is simple -- even austere --
similar to that of invoking and chaining together utilities at the command line, and there are only a few "rules"
governing their use. Most short scripts work right the first time, and debugging even the longer ones is
straightforward.
In the early days of personal computing, the BASIC language enabled
anyone reasonably computer proficient to write programs on an early
generation of microcomputers. Decades later, the Bash scripting
language enables anyone with a rudimentary knowledge of Linux or
UNIX to do the same on modern machines.
We now have miniaturized single-board computers with amazing
capabilities, such as the Raspberry Pi.
Bash scripting provides a way to explore the capabilities of these
fascinating devices.
A shell script is a quick-and-dirty method of prototyping a complex application. Getting even a limited subset
of the functionality to work in a script is often a useful first stage in project development. In this way, the
structure of the application can be tested and tinkered with, and the major pitfalls found before proceeding to
the final coding in C , C++ , Java , Perl, or Python.
Shell scripting hearkens back to the classic UNIX philosophy of breaking complex projects into simpler
subtasks, of chaining together components and utilities. Many consider this a better, or at least more
esthetically pleasing approach to problem solving than using one of the new generation of high-powered
all-in-one languages, such as Perl , which attempt to be all things to all people, but at the cost of forcing you to
alter your thinking processes to fit the tool.
According to Herbert Mayer, "a useful language needs arrays, pointers, and a generic mechanism for building
data structures." By these criteria, shell scripting falls somewhat short of being "useful." Or, perhaps not....
When not to use shell scripts
Chapter 1. Shell Programming! 1
- Resource-intensive tasks, especially where speed is a factor (sorting, hashing, recursion [2] ...)
Procedures involving heavy-duty math operations, especially floating point arithmetic, arbitrary
precision calculations, or complex numbers (use C++ or FORTRAN instead)
- Cross-platform portability required (use C or Java instead)
Complex applications, where structured programming is a necessity (type-checking of variables,
function prototypes, etc.)
- Mission-critical applications upon which you are betting the future of the company
Situations where security is important, where you need to guarantee the integrity of your system and
protect against intrusion, cracking, and vandalism
- Project consists of subcomponents with interlocking dependencies
Extensive file operations required ( Bash is limited to serial file access, and that only in a
particularly clumsy and inefficient line-by-line fashion.)
- Need native support for multi-dimensional arrays
- Need data structures, such as linked lists or trees
- Need to generate / manipulate graphics or GUIs
- Need direct access to system hardware or external peripherals
- Need port or socket I/O
- Need to use libraries or interface with legacy code
Proprietary, closed-source applications (Shell scripts put the source code right out in the open for all
the world to see.)
If any of the above applies, consider a more powerful scripting language -- perhaps Perl , Tcl , Python , Ruby
-- or possibly a compiled language such as C , C++ , or Java. Even then, prototyping the application as a
shell script might still be a useful development step.
We will be using Bash, an acronym [3] for "Bourne-Again shell" and a pun on Stephen Bourne's now classic
Bourne shell. Bash has become a de facto standard for shell scripting on most flavors of UNIX. Most of the
principles this book covers apply equally well to scripting with other shells, such as the Korn Shell , from
which Bash derives some of its features, [4] and the C Shell and its variants. (Note that C Shell programming
is not recommended due to certain inherent problems, as pointed out in an October, 1993 Usenet post by Tom
Christiansen.)
What follows is a tutorial on shell scripting. It relies heavily on examples to illustrate various features of the
shell. The example scripts work -- they've been tested, insofar as possible -- and some of them are even useful
in real life. The reader can play with the actual working code of the examples in the source archive
(scriptname.sh or scriptname.bash), [5] give them execute permission ( chmod u+rx
scriptname ), then run them to see what happens. Should the source archive not be available, then
cut-and-paste from the HTML or pdf rendered versions. Be aware that some of the scripts presented here
introduce features before they are explained, and this may require the reader to temporarily skip ahead for
enlightenment.
Unless otherwise noted, the author of this book wrote the example scripts that follow.
His countenance was bold and bashed not.
--Edmund Spenser
Chapter 1. Shell Programming! 2
Warning:
-------
This script uses quite a number of features that will be explained
#+ later on.
By the time you've finished the first half of the book,
#+ there should be nothing mysterious about it.
LOG_DIR=/var/log ROOT_UID=0 # Only users with $UID 0 have root privileges. LINES=50 # Default number of lines saved. E_XCD=86 # Can't change directory? E_NOTROOT=87 # Non-root exit error.
Run as root, of course.
if [ "$UID" -ne "$ROOT_UID" ] then echo "Must be root to run this script." exit $E_NOTROOT fi
if [ -n "$1" ]
Test whether command-line argument is present (non-empty).
then lines=$ else lines=$LINES # Default, if not specified on command-line. fi
Stephane Chazelas suggests the following,
#+ as a better way of checking command-line arguments, #+ but this is still a bit advanced for this stage of the tutorial.
E_WRONGARGS=85 # Non-numerical argument (bad argument format).
case "$1" in
"" ) lines=50;;
[!0-9]) echo "Usage: basename $0 lines-to-cleanup";
exit $E_WRONGARGS;;
* ) lines=$1;;
esac
#* Skip ahead to "Loops" chapter to decipher all this.
cd $LOG_DIR
if [ pwd != "$LOG_DIR" ] # or if [ "$PWD" != "$LOG_DIR" ]
Not in /var/log?
then echo "Can't change to $LOG_DIR." exit $E_XCD fi # Doublecheck if in right directory before messing with log file.
Far more efficient is:
cd /var/log || {
echo "Cannot change to necessary directory." >&
exit $E_XCD;
Chapter 2. Starting Off With a Sha-Bang 4
tail -n $lines messages > mesg.temp # Save last section of message log file. mv mesg.temp messages # Rename it as system log file.
cat /dev/null > messages
#* No longer needed, as the above method is safer.
cat /dev/null > wtmp # ': > wtmp' and '> wtmp' have the same effect. echo "Log files cleaned up."
Note that there are other log files in /var/log not affected
#+ by this script.
exit 0
A zero return value from the script upon exit indicates success
#+ to the shell.
Since you may not wish to wipe out the entire system log, this version of the script keeps the last section of
the message log intact. You will constantly discover ways of fine-tuning previously written scripts for
increased effectiveness.
The sha-bang ( #!) [6] at the head of a script tells your system that this file is a set of commands to be fed to
the command interpreter indicated. The #! is actually a two-byte [7] magic number , a special marker that
designates a file type, or in this case an executable shell script (type man magic for more details on this
fascinating topic). Immediately following the sha-bang is a path name. This is the path to the program that
interprets the commands in the script, whether it be a shell, a programming language, or a utility. This
command interpreter then executes the commands in the script, starting at the top (the line following the
sha-bang line), and ignoring comments. [8]
#!/bin/sh #!/bin/bash #!/usr/bin/perl #!/usr/bin/tcl #!/bin/sed -f #!/bin/awk -f
Each of the above script header lines calls a different command interpreter, be it /bin/sh, the default shell
( bash in a Linux system) or otherwise. [9] Using #!/bin/sh , the default Bourne shell in most commercial
variants of UNIX, makes the script portable to non-Linux machines, though you sacrifice Bash-specific
features. The script will, however, conform to the POSIX [10] sh standard.
Note that the path given at the "sha-bang" must be correct, otherwise an error message -- usually "Command
not found." -- will be the only result of running the script. [11]
#! can be omitted if the script consists only of a set of generic system commands, using no internal shell
directives. The second example, above, requires the initial #!, since the variable assignment line, lines=50 ,
uses a shell-specific construct. [12] Note again that #!/bin/sh invokes the default shell interpreter, which
defaults to /bin/bash on a Linux machine.
This tutorial encourages a modular approach to constructing a script. Make note of and collect
"boilerplate" code snippets that might be useful in future scripts. Eventually you will build quite an
Chapter 2. Starting Off With a Sha-Bang 5
Part 2. Basics
Table of Contents
3. Special Characters
4. Introduction to Variables and Parameters
4.1. Variable Substitution
4.2. Variable Assignment
4.3. Bash Variables Are Untyped
4.4. Special Variable Types
5. Quoting
5.1. Quoting Variables
5.2. Escaping
6. Exit and Exit Status
7. Tests
7.1. Test Constructs
7.2. File test operators
7.3. Other Comparison Operators
7.4. Nested if/then Condition Tests
7.5. Testing Your Knowledge of Tests
8. Operations and Related Topics
8.1. Operators
8.2. Numerical Constants
8.3. The Double-Parentheses Construct
8.4. Operator Precedence
Part 2. Basics 7
Chapter 3. Special Characters
What makes a character special? If it has a meaning beyond its literal meaning , a meta-meaning, then we refer
to it as a special character. Along with commands and keywords, special characters are building blocks of
Bash scripts.
Special Characters Found In Scripts and Elsewhere
Comments. Lines beginning with a # (with the exception of #!) are comments and will not be
executed.
This line is a comment.
Comments may also occur following the end of a command.
echo "A comment will follow." # Comment here.
^ Note whitespace before
Comments may also follow whitespace at the beginning of a line.
A tab precedes this comment.
Comments may even be embedded within a pipe.
initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\n' |\
Delete lines containing '#' comment character.
sed -e 's/./. /g' -e 's// /g'` )
Excerpted from life.sh script
A command may not follow a comment on the same line. There is no method of
terminating the comment, in order for "live code" to begin on the same line. Use a new
line for the next command.
Of course, a quoted or an escaped # in an echo statement does not begin a comment.
Likewise, a # appears in certain parameter-substitution constructs and in numerical
constant expressions.
echo "The # here does not begin a comment." echo 'The # here does not begin a comment.' echo The # here does not begin a comment. echo The # here begins a comment.
echo ${PATH#*:} # Parameter substitution, not a comment. echo $(( 2#101011 )) # Base conversion, not a comment.
Thanks, S.C.
The standard quoting and escape characters (" ' ) escape the #.
Certain pattern matching operations also use the #.
Command separator [semicolon]. Permits putting two or more commands on the same line.
echo hello; echo there
Chapter 3. Special Characters 8
bash$ cp /home/bozo/current_work/junk/.*
Copy all the "junk" files to $PWD.
"dot" character match. When matching characters, as part of a regular expression, a "dot" matches a
single character.
partial quoting [double quote]. "STRING" preserves (from interpretation) most of the special
characters within STRING. See Chapter 5.
full quoting [single quote]. 'STRING' preserves all special characters within STRING. This is a
stronger form of quoting than "STRING". See Chapter 5.
comma operator. The comma operator [16] links together a series of arithmetic operations. All are
evaluated, but only the last one is returned.
let "t2 = ((a = 9, 15 / 3))"
Set "a = 9" and "t2 = 15 / 3"
The comma operator can also concatenate strings.
for file in /{,usr/}bin/*calc
^ Find all executable files ending in "calc"
#+ in /bin and /usr/bin directories. do if [ -x "$file" ] then echo $file fi done
/bin/ipcalc
/usr/bin/kcalc
/usr/bin/oidcalc
/usr/bin/oocalc
Thank you, Rory Winston, for pointing this out.
Lowercase conversion in parameter substitution (added in version 4 of Bash).
\
escape [backslash]. A quoting mechanism for single characters.
\X escapes the character X. This has the effect of "quoting" X , equivalent to 'X'. The \ may be used to
quote " and ', so they are expressed literally.
See Chapter 5 for an in-depth explanation of escaped characters.
Filename path separator [forward slash]. Separates the components of a filename (as in
/home/bozo/projects/Makefile).
This is also the division arithmetic operator.
`
command substitution. The command construct makes available the output of command for
assignment to a variable. This is also known as backquotes or backticks.
Chapter 3. Special Characters 10
null command [colon]. This is the shell equivalent of a "NOP" ( no op , a do-nothing operation). It
may be considered a synonym for the shell builtin true. The ":" command is itself a Bash builtin, and
its exit status is true (0).
echo $? # 0
Endless loop:
while : do operation- operation- ... operation-n done
Same as:
while true
do
...
done
Placeholder in if/then test:
if condition then : # Do nothing and branch ahead else # Or else ... take-some-action fi
Provide a placeholder where a binary operation is expected, see Example 8-2 and default parameters.
: ${username=whoami}
${username=whoami} Gives an error without the leading :
unless "username" is a command or builtin...
: ${1?"Usage: $0 ARGUMENT"} # From "usage-message.sh example script.
Provide a placeholder where a command is expected in a here document. See Example 19-10.
Evaluate string of variables using parameter substitution (as in Example 10-7).
: ${HOSTNAME?} ${USER?} ${MAIL?}
Prints error message
#+ if one or more of essential environmental variables not set.
Variable expansion / substring replacement.
In combination with the > redirection operator, truncates a file to zero length, without changing its
permissions. If the file did not previously exist, creates it.
: > data.xxx # File "data.xxx" now empty.
Same effect as cat /dev/null >data.xxx
However, this does not fork a new process, since ":" is a builtin.
See also Example 16-15.
Chapter 3. Special Characters 11
The * also represents any number (or zero) characters in a regular expression.
arithmetic operator. In the context of arithmetic operations, the * denotes multiplication.
** A double asterisk can represent the exponentiation operator or extended file-match globbing.
test operator. Within certain expressions, the? indicates a test for a condition.
In a double-parentheses construct, the? can serve as an element of a C-style trinary operator. [17]
condition? result-if-true : result-if-false
(( var0 = var1<98?9:21 ))
^ ^
if [ "$var1" -lt 98 ]
then
var0=
else
var0=
fi
In a parameter substitution expression, the? tests whether a variable has been set.
wild card. The? character serves as a single-character "wild card" for filename expansion in
globbing, as well as representing one character in an extended regular expression.
Variable substitution (contents of a variable).
var1= var2=23skidoo
echo $var1 # 5 echo $var2 # 23skidoo
A $ prefixing a variable name indicates the value the variable holds.
end-of-line. In a regular expression, a "$" addresses the end of a line of text.
Parameter substitution.
Quoted string expansion. This construct expands single or multiple escaped octal or hex values into
ASCII [18] or Unicode characters.
positional parameters.
exit status variable. The $? variable holds the exit status of a command, a function, or of the script
itself.
process ID variable. The $$ variable holds the process ID [19] of the script in which it appears.
command group.
Chapter 3. Special Characters 13
(a=hello; echo $a)
A listing of commands within parentheses starts a subshell.
Variables inside parentheses, within the subshell, are not visible to the rest of the
script. The parent process, the script, cannot read variables created in the child
process, the subshell.
a= ( a=321; )
echo "a = $a" # a = 123
"a" within parentheses acts like a local variable.
array initialization.
Array=(element1 element2 element3)
{xxx,yyy,zzz,...}
Brace expansion.
echo "{These,words,are,quoted}" # " prefix and suffix
"These" "words" "are" "quoted"
cat {file1,file2,file3} > combined_file
Concatenates the files file1, file2, and file3 into combined_file.
cp file22.{txt,backup}
Copies "file22.txt" to "file22.backup"
A command may act upon a comma-separated list of file specs within braces. [20] Filename
expansion (globbing) applies to the file specs between the braces.
No spaces allowed within the braces unless the spaces are quoted or escaped.
echo {file1,file2}\ :{\ A," B",' C'}
file1 : A file1 : B file1 : C file2 : A file2 : B file2 :
C
{a..z}
Extended Brace expansion.
echo {a..z} # a b c d e f g h i j k l m n o p q r s t u v w x y z
Echoes characters between a and z.
echo {0..3} # 0 1 2 3
Echoes characters between 0 and 3.
base64_charset=( {A..Z} {a..z} {0..9} + / = )
Initializing an array, using extended brace expansion.
From vladz's "base64.sh" example script.
The {a..z} extended brace expansion construction is a feature introduced in version 3 of Bash.
Block of code [curly brackets]. Also referred to as an inline group , this construct, in effect, creates
an anonymous function (a function without a name). However, unlike in a "standard" function, the
Chapter 3. Special Characters 14