[TOC]
Variables
Shell variables are created once they are assigned a value. A variable can contain a number, a character or a string of characters. Variable name is case sensitive and can consist of a combination of letters and the underscore "_". Value assignment is done using the "=" sign. Note that no space permitted on either side of = sign when initializing variables.
PRICE_PER_APPLE=5
MyFirstLetters=ABC
greeting='Hello world!'
Referencing the variables
A backslash "" is used to escape special character meaning
PRICE_PER_APPLE=5
echo "The price of an Apple today is: $HK {} is used to avoid ambiguity
MyFirstLetters=ABC
echo "The first 10 letters in the alphabet are: ${MyFirstLetters}DEFGHIJ"
Encapsulating the variable name with "" will preserve any white space values
greeting='Hello world!'
echo greeting"
Variables can be assigned with the value of a command output. This is referred to as substitution. Substitution can be done by encapsulating the command with `` (known as back-ticks) or with $()
FILELIST=ls
FileWithTimeStamp=/tmp/my-dir/file_() parenthesis and capture its output.
Arrays
An array can hold several values under one name. Array naming is the same as variables naming. An array is initialized by assign space-delimited values enclosed in ()
my_array=(apple banana "Fruit Basket" orange)
new_array[2]=apricot
Array members need not be consecutive or contiguous. Some members of the array can be left uninitialized.
The total number of elements in the array is referenced by ${#arrayname[@]}
my_array=(apple banana "Fruit Basket" orange)
echo ${#my_array[@]} # 4
The array elements can be accessed with their numeric index. The index of the first element is 0.
my_array=(apple banana "Fruit Basket" orange)
echo ${my_array[3]} # orange - note that curly brackets are needed
# adding another array element
my_array[4]="carrot" # value assignment without a $ and curly brackets
echo ${#my_array[@]} # 5
echo ${my_array[${#my_array[@]}-1]} # carrot
Basic Operators
Arithmetic Operators
Simple arithmetics on variables can be done using the arithmetic expression: $((expression))
A=3
B=$((100 * $A + 5)) # 305
Basic String Operations
The shell allows some common string operations which can be very useful for script writing.
String Length
# 1234567890123456
STRING="this is a string"
echo ${#STRING} # 16
Index
Find the numerical position in SUBSTRING that matches. Note that the 'expr' command is used in this case.
Substring Extraction
Extract substring of length STRING starting after position $POS. Note that first position is 0.
STRING="this is a string"
POS=1
LEN=3
echo ${STRING:$POS:$LEN} # his
Decision Making
As in popular programming languages, the shell also supports logical decision making.
The basic conditional decision making construct is:
if [ expression ]; then
code if 'expression' is true
fi
NAME="John"
if [ "$NAME" = "John" ]; then
echo "True - my name is indeed John"
fi
It can be expanded with 'else'
NAME="Bill"
if [ "$NAME" = "John" ]; then
echo "True - my name is indeed John"
else
echo "False"
echo "You must mistaken me for $NAME"
fi
It can be expanded with 'elif' (else-if)
NAME="George"
if [ "$NAME" = "John" ]; then
echo "John Lennon"
elif [ "$NAME" = "George" ]; then
echo "George Harrison"
else
echo "This leaves us with Paul and Ringo"
fi
Types of numeric comparisons
comparison Evaluated to true when
$a -lt $b $a < $b
$a -gt $b $a > $b
$a -le $b $a <= $b
$a -ge $b $a >= $b
$a -eq $b $a is equal to $b
$a -ne $b $a is not equal to $b
Types of string comparisons
comparison Evaluated to true when
"$a" = "$b" $a is the same as $b
"$a" == "$b" $a is the same as $b
"$a" != "$b" $a is different from $b
-z "$a" $a is empty
Loops
bash for loop
for arg in [list]
do
command(s)...
done
For each pass through the loop, arg takes on the value of each successive value in the list. Then the command(s) are executed.
# loop on array member
NAMES=(Joe Jenny Sara Tony)
for N in ${NAMES[@]} ; do
echo "My name is $N"
done
# loop on command output results
for f in $( ls prog.sh /etc/localtime ) ; do
echo "File is: $f"
done
bash while loop
# basic construct
while [ condition ]
do
command(s)...
done
The while construct tests for a condition, and if true, executes commands. It keeps looping as long as the condition is true.
COUNT=4
while [ $COUNT -gt 0 ]; do
echo "Value of count is: $COUNT"
COUNT=$(($COUNT - 1))
done
"break" and "continue" statements
break and continue can be used to control the loop execution of for, while and until constructs. continue is used to skip the rest of a particular loop iteration, whereas break is used to skip the entire rest of loop. A few examples:
# Prints out 0,1,2,3,4
COUNT=0
while [ $COUNT -ge 0 ]; do
echo "Value of COUNT is: $COUNT"
COUNT=$((COUNT+1))
if [ $COUNT -ge 5 ] ; then
break
fi
done
# Prints out only odd numbers - 1,3,5,7,9
COUNT=0
while [ $COUNT -lt 10 ]; do
COUNT=$((COUNT+1))
# Check if COUNT is even
if [ $(($COUNT % 2)) = 0 ] ; then
continue
fi
echo $COUNT
done
count=4; while [ count"; count=$((count-1)); done
Array-Comparison
Comparison of arrays Shell can handle arrays 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.
# basic construct
# array=(value1 value2 ... valueN)
array=(23 45 34 1 2 3)
#To refer to a particular value (e.g. : to refer 3rd value)
echo ${array[2]}
#To refer to all the array values
echo ${array[@]}
#To evaluate the number of elements in an array
echo ${#array[@]}
Shell Functions
Like other programming languages, the shell may have functions. A function is a subroutine that implements a set of commands and operations. It is useful for repeated tasks.
# basic construct
function_name {
command...
}
Functions are called simply by writing their names. A function call is equivalent to a command. Parameters may be passed to a function, by specifying them after the function name. The first parameter is referred to in the function as 2 etc.
function function_B {
echo "Function B."
}
function function_A {
echo "$1"
}
function adder {
echo "$(($1 + $2))"
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A." # Function A.
function_B # Function B.
# Pass two parameters to function adder
adder 12 56 # 68
In last tutorial about shell function, you use "$1" represent the first argument passed to function_A. Moreover, here are some special variables in shell:
n - The Nth argument passed to script was invoked or function was called.|
@ - All arguments passed to script or function.|
? - The exit status of the last command executed.|
$$ - The process ID of the current shell. For shell scripts, this is the process ID under which they are executing.|
$! - The process number of the last background command
Example:
#!/bin/bash
echo "Script Name: $0"
function func {
for var in $*
do
let i=i+1
echo "The \$${i} argument is: ${var}"
done
echo "Total count of arguments: $#"
}
func We are argument
* have different behavior when they were enclosed in double quotes.
#!/bin/bash
function func {
echo "--- \"\$*\""
for ARG in "$*"
do
echo $ARG
done
echo "--- \"\$@\""
for ARG in "$@"
do
echo $ARG
done
}
func We are argument
网友评论