Bash Scripting Notes and Tips
Bash Scripting Notes and Tips
Bash Scripting Notes and Tips
(on
Bash uses certain shell variables in the same way as the Bourne shell. In some cases,
Bash assigns a default value to the variable. The table below gives an overview of
these plain shell variables:
Table 3-1. Reserved Bourne shell variables
Variable
name
Definition
CDPATH
HOME
The current user's home directory; the default for the cd built-in. The
value of this variable is also used by tilde expansion.
IFS
A list of characters that separate fields; used when the shell splits words
2
Variable
name
Definition
as part of expansion.
If this parameter is set to a file name and the MAILPATH variable is not
set, Bash informs the user of the arrival of mail in the specified file.
MAILPATH
OPTARG
The value of the last option argument processed by the getopts builtin.
OPTIND
The index of the last option argument processed by the getopts builtin.
PATH
PS1
PS2
These variables are set or used by Bash, but other shells do not normally treat them
specially.
Table 3-2. Reserved Bash variables
Variable name
Definition
auto_resume
This variable controls how the shell interacts with the user and
job control.
BASH
BASH_ENV
BASH_VERSION
Variable name
Definition
information for this instance of Bash.
COLUMNS
COMP_CWORD
COMP_LINE
COMP_POINT
COMP_WORDS
COMPREPLY
DIRSTACK
EUID
FCEDIT
FIGNORE
FUNCNAME
GLOBIGNORE
GROUPS
histchars
HISTCMD
Variable name
Definition
HISTCONTROL
HISTFILE
The name of the file to which the command history is saved. The
default value is ~/.bash_history.
HISTFILESIZE
HISTIGNORE
HISTSIZE
HOSTFILE
HOSTNAME
HOSTTYPE
IGNOREEOF
INPUTRC
LANG
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MESSAGES
This variable determines the locale used to translate doublequoted strings preceded by a "$" sign.
Variable name
Definition
LC_NUMERIC
LINENO
LINES
MACHTYPE
MAILCHECK
How often (in seconds) that the shell should check for mail in the
files specified in the MAILPATH or MAIL variables.
OLDPWD
OPTERR
OSTYPE
PIPESTATUS
POSIXLY_CORREC If this variable is in the environment when bash starts, the shell
T
enters POSIX mode.
PPID
PS4
PWD
RANDOM
Variable name
Definition
REPLY
SECONDS
SHELLOPTS
SHLVL
TIMEFORMAT
TMOUT
UID
Check the Bash man, info or doc pages for extended information. Some variables are
read-only, some are set automatically and some lose their meaning when set to a
different value than the default.
Special parameters
The shell treats several parameters specially. These parameters may only be
referenced; assignment to them is not allowed.
Table 3-3. Special bash variables
Charac
Definition
ter
$*
$@
Charac
Definition
ter
$#
$?
$-
$$
$!
$0
$_
The underscore variable is set at shell startup and contains the absolute
file name of the shell or script being executed as passed in the argument
list. Subsequently, it expands to the last argument to the previous
command, after expansion. It is also set to the full pathname of each
command executed and placed in the environment exported to that
command. When checking mail, this parameter holds the name of the mail
file.
$* vs. $@
The implementation of "$*" has always been a problem and realistically should have
been replaced with the behavior of "$@". In almost every case where coders use "$*",
they mean "$@". "$*" Can cause bugs and even security holes in your software.
The positional parameters are the words following the name of a shell script. They are
put into the variables $1, $2, $3 and so on. As long as needed, variables are added to an
internal array. $# holds the total number of parameters, as is demonstrated with this
simple script:
#!/bin/bash
# positional.sh
# This script reads 3 positional parameters and prints them out.
POSPAR1="$1"
POSPAR2="$2"
POSPAR3="$3"
echo
echo
echo
echo
echo
User franky starts entering the grep command, which results in the assignment of
the _ variable. The process ID of his shell is 10662. After putting a job in the
background, the ! holds the process ID of the backgrounded job. The shell running
is bash. When a mistake is made, ? holds an exit code different from 0 (zero).
Redirections
If you want to redirect std out,err,input into a black hole use
2> /dev/null
Escape characters are used to remove the special meaning
from a single character. A non-quoted backslash, \, is used as
an escape character in Bash.
& will run in background
&& means AND
&> FILE
- both standard output and standard error to be
redirected to the file
<& File
- both standard input and standard error to be
redirected to the file
Single quotes
Single quotes ('') are used to preserve the literal value of each character enclosed
within the quotes. A single quote may not occur between single quotes, even when
preceded by a backslash.
We continue with the previous example:
franky ~> echo '$date'
$date
Double quotes
Using double quotes the literal value of all characters enclosed is preserved, except for
the dollar sign, the backticks (backward single quotes, ``) and the backslash.
The dollar sign and the backticks retain their special meaning within the double
quotes.
10
The backslash retains its meaning only when followed by dollar, backtick, double
quote, backslash or newline. Within double quotes, the backslashes are removed from
the input stream when followed by one of these characters. Backslashes preceding
characters that don't have a special meaning are left unmodified for processing by the
shell interpreter.
A double quote may be quoted within double quotes by preceding it with a backslash.
franky ~> echo "$date"
20021226
franky ~> echo "`date`"
Sun Apr 20 11:22:06 CEST 2003
franky ~> echo "I'd say: \"Go for it!\""
I'd say: "Go for it!"
franky ~> echo "\"
More input>"
franky ~> echo "\\"
\
The following construct allows for creation of the named variable if it does not
yet exist:
${VAR:=value}
Example:
franky ~> echo $FRANKY
franky ~> echo ${FRANKY:=Franky}
Franky
Operat
Effect
or
.
{N}
{N,}
{N,M}
The preceding item is matched at least N times, but not more than M
times.
represents the range if it's not first or last in a list or the ending point of a
range in a list.
Matches the empty string at the beginning of a line; also represents the
characters not in the range of a list.
\b
\B
Matches the empty string provided it's not at the edge of a word.
\<
\>
12
Arithmetic Operators:
There are following arithmetic operators supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then:
Operator Description
Example
Modulus - Divides left hand operand by right hand operand and returns
remainder
==
Equality - Compares two numbers, if both are same then returns true.
!=
Not Equality - Compares two numbers, if both are different then returns true.
Modulus %
into a
meaning:
13
Exercises
Display configuration files in /etc that contain numbers in their names.
# ls a /etc/ | grep [*0-9*]
From the /etc/group directory, display all lines starting with the
string "daemon".
# grep ^daemon /etc/group
Print all the lines from the same file that don't contain the string.
# grep v ^daemon /etc/group
Display localhost information from the /etc/hosts file, display the line
number(s) matching the search string and count the number of
occurrences of the string.
# grep c (used for counting). See script ~/SCRIPTS/count.sh
How many README files do these subdirectories contain? Don't count
anything in the form of "README.a_string".
# ls a /usr/share/doc/* | grep c ^README$
Make a list of files in your home directory that were changed less that 10
hours ago, using grep, but leave out directories.
# ls alR /home/*
Result
a\
14
Command
Result
c\
Delete text.
i\
Print text.
Read a file.
Write to a file.
Apart from editing commands, you can give options to sed. An overview is in the
table below:
Table 5-2. Sed options
Option
Effect
-e
SCRIPT
Add the commands in SCRIPT to the set of commands to be run while processing the
input.
-f
Add the commands contained in the file SCRIPT-FILE to the set of commands to be
run while processing the input.
-n
Silent mode.
-V
-e
options:
s/ = for replace
/g = to replace patern on entire line not just first occurrence.
Exercises
1. Make a list of files in /usr/bin that have the letter "a" as the second character.
Put the result in a temporary file.
ls /usr/bin | grep ^.a.*
2. Delete the first 3 lines of each temporary file.
15
16
Sequence
Meaning
\a
Bell character
\n
Newline character
\t
Tab
Example:
df -h | sort -rnk 5 | head -3 | \
awk '{ print "Partition " $6 "\t: " $5 " full!" }'
Partition /var : 86% full!
Partition /usr : 85% full!
Partition /home : 70% full!
The END statement can be added for inserting text after the entire input is processed:
kelly is in /etc> ls -l | \
awk '/\<[a|x].*\.conf$/ { print $9 } END { print \
"Can I do anything else for you, mistress?" }'
amd.conf
antivir.conf
xcdroast.conf
xinetd.conf
Can I do anything else for you, mistress?
kelly is in /etc>
17
Built in awk variable is FS, edit this variable to define tab delimiter
for $1, $2, $n. Always use BEGIN statement to assign FS a value.
Ex: In the example below, we build a command that displays all the users on your
Fields are normally separated by spaces in the output. This becomes apparent when
you use the correct syntax for the print command, where arguments are separated by
commas:
!! by default if you put print $1,$2 the outbul delimiter will be a blank space. IF you
specify BEGIN OFS=- , when printing $1,$2 it will output 1-2
kelly@octarine ~/test> cat test
record1
data1
record2
data2
kelly@octarine ~/test> awk '{ print $1 $2}' test
record1data1
record2data2
ORS
18
The built-in NR holds the number of records that are processed. It is incremented after
reading a new input line. You can use it at the end to count the total number of
records, or in each output record:
kelly@octarine ~/test> cat processed.awk
BEGIN { OFS="-" ; ORS="\n--> done\n" }
{ print "Record number " NR ":\t" $1,$2 }
END { print "Number of records processed: " NR }
kelly@octarine ~/test> awk -f processed.awk test
Record number 1:
record1-data1
--> done
Record number 2:
record2-data2
--> done
Number of records processed: 2
--> done
kelly@octarine ~/test>
Apart from the built-in variables, you can define your own. When awk encounters a
reference to a variable which does not exist (which is not predefined), the variable is
created and initialized to a null string. For all subsequent references, the value of the
variable is whatever value was assigned last. Variables can be a string or a numeric
value. Content of input fields can also be assigned to variables.
Values can be assigned directly using the = operator, or you can use the current value
of the variable in combination with other operators:
kelly@octarine ~> cat revenues
20021009
20021013
20021015
20021020
20021112
20021123
20021204
20021215
consultancy
training
appdev
training
BigComp
EduComp
SmartComp
EduComp
2500
2000
10000
5000
19
Exercises
1. For the first exercise, your input is lines in the following form:
Username:Firstname:Lastname:Telephone number
Make an awk script that will convert such a line to an LDAP record in this format:
dn: uid=Username, dc=example, dc=com
cn: Firstname Lastname
sn: Lastname
telephoneNumber: Telephone number
see ~/SCRIPTS/AWK/awk1.awk
2. Create a Bash script using awk and standard UNIX commands that will show the top three users
of disk space in the /home file system (if you don't have the directory holding the homes on a
separate partition, make the script for the / partition; this is present on every UNIX system). First,
execute the commands from the command line. Then put them in a script. The script should
create sensible output (sensible as in readable by the boss). If everything proves to work, have
the script email its results to you (use for instance mail -s Disk space
usage <you@your_comp> < result)
See
~/SCRIPTS/AWK/awk2.sh
20
Primary
Meaning
[ -a FILE ]
[ -b FILE ]
[ -c FILE ]
[ -d FILE ]
[ -e FILE ]
[ -f FILE ]
[ -g FILE ]
[ -h FILE ]
[ -k FILE ]
[ -p FILE ]
[ -r FILE ]
[ -s FILE ]
[ -t FD ]
[ -u FILE ]
True if FILE exists and its SUID (set user ID) bit is set.
[ -w FILE ]
[ -x FILE ]
[ -O FILE ]
[ -G FILE ]
[ -L FILE ]
[ -N FILE ]
True if FILE exists and has been modified since it was last read.
[ -S FILE ]
[ FILE1 -ot FILE2 ] True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not.
[ FILE1 -ef FILE2 ] True if FILE1 and FILE2 refer to the same device and inode numbers.
[ -o OPTIONNAM
True if shell option "OPTIONNAME" is enabled.
E]
[ -z
STRING ]
STRING ] or [
True if the length of "STRING" is non-zero.
STRING ]
[ -n
[ STRING1 ==
STRING2 ]
True if the strings are equal. "=" may be used instead of "==" for strict
POSIX compliance.
[ STRING1 !=
STRING2 ]
21
Primary
Meaning
[ STRING1 <
STRING2 ]
[ STRING1 >
STRING2 ]
"OP" is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary
operators return true if "ARG1" is equal to, not equal to, less than, less
[ ARG1 OP ARG2 ]
than or equal to, greater than, or greater than or equal to"ARG2",
respectively. "ARG1" and "ARG2" are integers.
!!!
$# refers to the number of command line arguments. $0 refers
to the name of the script. !!!!!
* if/then/elif/else constructs
Boolean operations
The above script can be shortened using the Boolean operators "AND" (&&)
and "OR" (||).
Arithmetic expansion allows the evaluation of an arithmetic expression and the
substitution of the result. The format for arithmetic expansion is:
$(( EXPRESSION )) do not use square brackets [].!!!
Example using Boolean operators
22
We use the double brackets for testing an arithmetic expression, see Section 3.4.6.
This is equivalent to the let statement. You will get stuck using square brackets here, if
you try something like $[$year % 400], because here, the square brackets don't
represent an actual command by themselves.
Among other editors, gvim is one of those supporting colour schemes according to the
file format; such editors are useful for detecting errors in your code.
We already briefly met the exit statement in Section 7.2.1.3. It terminates execution of
the entire script. It is most often used if the input requested from the user is incorrect,
if a statement did not run successfully or if some other error occurred.
The exit statement takes an optional argument. This argument is the integer exit status
code, which is passed back to the parent and stored in the $? variable.
A zero argument means that the script ran successfully. Any other value may be used
by programmers to pass back different messages to the parent, so that different actions
can be taken according to failure or success of the child process. If no argument is
given to the exit command, the parent shell uses the current value of the $? variable.
23
Below is an example with a slightly adapted penguin.sh script, which sends its exit
status back to the parent, feed.sh:
anny ~/testdir> cat penguin.sh
#!/bin/bash
# This script lets you present different menus to Tux. He will only be happy
# when given a fish. We've also added a dolphin and (presumably) a camel.
if [ "$menu" == "fish" ]; then
if [ "$animal" == "penguin" ]; then
echo "Hmmmmmm fish... Tux happy!"
elif [ "$animal" == "dolphin" ]; then
echo "Pweetpeettreetppeterdepweet!"
else
echo "*prrrrrrrt*"
fi
else
if [ "$animal" == "penguin" ]; then
echo "Tux don't like that. Tux wants fish!"
exit 1
elif [ "$animal" == "dolphin" ]; then
echo "Pweepwishpeeterdepweet!"
exit 2
else
echo "Will you read this sign?!"
exit 3
fi
fi
This script is called upon in the next one, which therefore exports its
variables menu and animal:
anny ~/testdir> cat feed.sh
#!/bin/bash
# This script acts upon the exit status given by penguin.sh
export menu="$1"
export animal="$2"
feed="/nethome/anny/testdir/penguin.sh"
$feed $menu $animal
case $? in
1)
echo "Guard: You'd better give'm a fish, less they get violent..."
;;
2)
echo "Guard: It's because of people like you that they are leaving earth
all the time..."
;;
24
3)
echo "Guard: Buy the food that the Zoo provides for the animals, you ***,
how
do you think we survive?"
;;
*)
echo "Guard: Don't forget the guide!"
;;
esac
anny ~/testdir> ./feed.sh apple penguin
Tux don't like that. Tux wants fish!
Guard: You'd better give'm a fish, less they get violent...
As you can see, exit status codes can be chosen freely. Existing commands usually
have a series of defined codes; see the programmer's manual for each command for
more information.
25
case $space in
[1-6]*)
Message="All is quiet."
;;
[7-8]*)
Message="Start thinking about cleaning out some stuff. There's a partition
that is $space % full."
;;
9[1-8])
Message="Better hurry with that new disk... One partition is $space %
full."
;;
99)
Message="I'm drowning here! There's a partition at $space %!"
;;
*)
Message="I seem to be running with an nonexistent amount of disk space..."
;;
esac
echo $Message | mail -s "disk report `date`" anny
Exercises
3. Modify /etc/profile so that you get a special greeting message when you
connect to your system as root.
See edit from the end of /etc/profile
5.
6. Write a script that makes a backup of your home directory on a remote machine
using scp. The script should report in a log file, for
instance ~/log/homebackup.log. If you don't have a second machine to copy the
backup to, use scp to test copying it to the localhost. This requires SSH keys
between the two hosts, or else you have to supply a password. The creation of
SSH keys is explained in man ssh-keygen.
26
7.
The echo built-in command outputs its arguments, separated by spaces and terminated
with a newline character. The return status is always zero. echo takes a couple of
options:
-e:
-n:
Meaning
\a
Alert (bell).
\b
Backspace.
\c
\e
Escape.
\f
Form feed.
\n
Newline.
\r
Carriage return.
\t
Horizontal tab.
\v
Vertical tab.
\\
Backslash.
READ input
This will take input from user and assign variable ex:
echo Cati ani ai
27
read Varsta
echo $Varsta (valoarea variabilei va fi 25)
See script ~/SCRIPTS/READ/readtest.sh
Meaning
The words are assigned to sequential indexes of the array variable ANAME, starting at
-a ANAME 0. All elements are removed from ANAME before the assignment.
Other NAME arguments are ignored.
-d DELIM The first character of DELIM is used to terminate the input line, rather than newline.
-e
-n NCHARS
read returns after reading NCHARS characters rather than waiting for a complete line
of input.
-p PROMPT
Display PROMPT, without a trailing newline, before attempting to read any input. The
prompt is displayed only if input is coming from a terminal.
-r
If this option is given, backslash does not act as an escape character. The backslash is
considered to be part of the line. In particular, a backslash-newline pair may not be
used as a line continuation.
-s
Silent mode. If input is coming from a terminal, characters are not echoed.
Cause read to time out and return failure if a complete line of input is not read
-t TIMEOU within TIMEOUT seconds. This option has no effect if read is not reading input from
T
the terminal or from a pipe.
-u FD
If you put read xyz n 1 (read will return value after only 1
character input, and so on..) !!!
Stdin = 0
Stdout = 1
Stderr = 2
28
will
Exercises
1. Write a script that asks for the user's age. If it is equal to or
higher than 16, print a message saying that this user is allowed
to drink alcohol. If the user's age is below 16, print a message
telling the user how many years he or she has to wait before
legally being allowed to drink.
See script
See script ~/SCRIPTS/READ/exercise1.sh
29
2. Write a script that takes one file as an argument. Use a here document that
presents the user with a couple of choices for compressing the file. Possible
choices could be gzip, bzip2, compress and zip.
See script ~/SCRIPTS/READ/exercise2.sh
the system.
The first is a command line example, demonstrating the use of a for loop that makes a
backup copy of each .xml file. After issuing the command, it is safe to start working
on your sources:
[carol@octarine ~/articles] ls *.xml
file1.xml file2.xml file3.xml
[carol@octarine ~/articles] ls *.xml > list
[carol@octarine ~/articles] for i in `cat list`; do cp "$i" "$i".bak ; done
[carol@octarine ~/articles] ls *.xml*
file1.xml file1.xml.bak file2.xml file2.xml.bak
file3.xml
file3.xml.bak
Note the use of the date command to generate all kinds of file and directory names.
See the man page for more. Also sleep 300 (means waiting time 5 mins) until a new
file is created. !!!! The true statement will create files without stopping until a
force kill is performend by user (ctrl+c). !!!
Example:
An improved picturesort.sh script (see Section 9.2.2.2), which tests for available
disk space. If not enough disk space is available, remove pictures from the previous
months:
#!/bin/bash
# This script copies files from my homedirectory into the webserver
directory.
# A new directory is created every hour.
# If the pics are taking up too much space, the oldest are removed.
while true; do
DISKFUL=$(df -h $WEBDIR | grep -v File | awk '{print $5 }' | cut -d
"%" -f1 -)
until [ $DISKFUL -ge "90" ]; do
31
DATE=`date +%Y%m%d`
HOUR=`date +%H`
mkdir $WEBDIR/"$DATE"
while [ $HOUR -ne "00" ]; do
DESTDIR=$WEBDIR/"$DATE"/"$HOUR"
mkdir "$DESTDIR"
mv $PICDIR/*.jpg "$DESTDIR"/
sleep 3600
HOUR=`date +%H`
done
DISKFULL=$(df -h $WEBDIR | grep -v File | awk '{ print $5 }' | cut -d
"%" -f1 -)
done
TOREMOVE=$(find $WEBDIR -type d -a -mtime +30)
for i in $TOREMOVE; do
rm -rf "$i";
done
done
ARCHIVENR=`date +%Y%m%d`
DESTDIR="$PWD/archive-$ARCHIVENR"
mkdir "$DESTDIR"
# using quotes to catch file names containing spaces, using read -d for more
# fool-proof usage:
find "$PWD" -type f |
32
do
gzip "$file"; mv "$file".gz "$DESTDIR"
echo "$file archived"
done
See script /root/SCRIPTS/LOOPS/loop-withoutput-redirection/ loop-withoutput-redirection.sh
The break statement is used to exit the current loop before its
normal ending. This is done when you don't know in advance how
many times the loop will have to execute, for instance because it is
dependent on user input.
#!/bin/bash
# This script provides wisdom
# You can now exit in a decent way.
FORTUNE=/usr/games/fortune
while true; do
echo "On which topic do you want advice?"
echo "1. politics"
echo "2. startrek"
echo
echo -n "Enter your choice, or 0 for exit: "
read choice
echo
case $choice in
1)
$FORTUNE politics
;;
2)
$FORTUNE startrek
;;
0)
echo "OK, see you!"
break
;;
*)
echo "That is not a valid choice, try a number from 0 to 2."
;;
esac
done
tr = translate, convert or delete characters in a string. In our case this will convert from upper
case to lower case.
Also notice [:upper:] statement see this example:
Upon printing all the items, the PS3 prompt is printed and one line from standard input
is read. If this line consists of a number corresponding to one of the items, the value
of WORD is set to the name of that item. If the line is empty, the items and
the PS3 prompt are displayed again. If an EOF (End Of File) character is read, the loop
exits. Since most users don't have a clue which key combination is used for the EOF
sequence, it is more user-friendly to have a break command as one of the items. Any
other value of the read line will set WORD to be a null string.The read line is saved in
the REPLY variable.The RESPECTIVE-COMMANDS are executed after each
selection until the number representing the break is read. This exits the loop.
PS3 is a special variable that will output the value by itself.
Ex:
#!/bin/bash
echo "This script can make any of the files in this directory private."
echo "Enter the number of the file you want to protect:"
PS3="Your choice: "
#This will output after the 2 echos.
QUIT="QUIT THIS PROGRAM - I feel safe now."
touch "$QUIT"
select FILENAME in *;
do
case $FILENAME in
"$QUIT")
echo "Exiting."
Break
# break will exit the loop.
;;
*)
echo "You picked $FILENAME ($REPLY)"
chmod go-rwx "$FILENAME"
;;
esac
done
rm "$QUIT"
35
Exercises
1. Create a script that will take a (recursive) copy of files in /etc so that a
beginning system administrator can edit files without fear.
see script ~/SCRIPTS/LOOP/recursivecopy.sh
36
2. Write a script that takes exactly one argument, a directory name. If the number
of arguments is more or less than one, print a usage message. If the argument is
not a directory, print another message. For the given directory, print the five
biggest files and the five files that were most recently modified.
See script ~/SCRIPTS/LOOPS/2ndexercise.sh
3.
4. Write a script similar to the one in Section 9.5.1, but think of a way of quitting
after the user has executed 3 loops.
See script ~/SCRIPTS/LOOPS/4thexercise.sh
5.
Variable is an array.
37
Opti
Meaning
on
-f
-i
-p
-r
-t
-x
Mark each variable for export to subsequent commands via the environment.
Constants
In Bash, constants are created by making a variable read-only. The readonly built-in
marks each specified variable as unchangeable. The syntax is:
readonly OPTION VARIABLE(s)
38
Array variables
An array is a variable containing multiple values. Any variable may
be used as an array. There is no maximum limit to the size of an
array, nor any requirement that member variables be indexed or
assigned contiguously. Arrays are zero-based: the first element is
indexed with the number 0
Explicit declaration of an array is done using the declare built-in:
declare -a ARRAYNAME
A declaration with an index number will also be accepted, but the index number will
be ignored. Attributes to the array may be specified using
the declare and readonly built-ins. Attributes apply to all variables in the array; you
can't have mixed arrays.
Array variables may also be created using compound assignments in this format:
ARRAY=(value1
EX:
[bob in ~] ARRAY=(one two three)
[bob in ~] echo ${ARRAY[*]}
one two three
[bob in ~] echo $ARRAY[*]
one[*]
[bob in ~] echo ${ARRAY[2]}
three
[bob in ~] ARRAY[3]=four
[bob in ~] echo ${ARRAY[*]}
one two three four
Operations on variables
Length of a variable
If not,
Removing substrings
40
The opposite effect is obtained using "%" and "%%", as in this example
below. WORD should match a trailing portion of string:
[bob in ~] echo $STRING
thisisaverylongname
[bob in ~] echo ${STRING%name}
thisisaverylong
Exercises
1. See script ~/SCRIPTS/TypesofVariables/1stexercise.sh
41
In above example, test other_param will execute the test function with other_param
being 1st paramenter in the function.
42
Exercises
1 and 2. Type catman <ce vrei u> = functia e in /root/.bashrc
Signal value
Effect
SIGHUP
Hangup
SIGINT
SIGKILL
Kill signal
SIGTERM
15
Termination signal
SIGSTOP
17,19,23
done
43
Exercises
1. Create a script that writes a boot image to a diskette using the dd utility. If the user tries to
interrupt the script using Ctrl+C, display a message that this action will make the diskette
unusable.
See script ~/SCRIPTS/SIGNALS/createimages.sh
2. Wget http://.....
Tar xv (software name)
Trap echo SIGTERM SIGINT
Yum install y (software name).
END
44