Create variables
test="test"
homedir='pwd'
string="The man said \" hello \"."
Use the variable (using $)
homedir=$HOME
cd $homedir
Print variable
echo $s1
Pattern matching
* Match all characters in a string
? Match a single character
ls *.dat
Comments
# this is comment
Print string constant
echo 'hello'
echo "hello"
echo hello
Print string variable
x='Wonderful world'
echo $x
Running commands from script
ls
x='pwd'
$x
x='ls -l'
$x
u='-l'
x='ls '
$x $u
Use commands and string together
Back quotes are used to enclose commands.
An item enclosed in back quotes is replaced by the standard output of the command.
date=`date`
echo the date is $date
Read text from keyboard
read x
echo $x
Many commands in one line
echo "a"; echo "b"; echo "c"
var=5; echo `expr $var + $var`
Integer arithmetics + - * / %
#!/bin/bash
let sum=$x+$y
echo 'x+y=' $sum
#!/bin/sh
sum=`expr $x + $y`
echo $sum
if statement
#!/bin/sh
if [ $x -eq 5 ]
then
echo "five"
fi
if / else statement
if [ $x -eq 5 ]
then
echo "five"
else
echo "not 5"
fi
if / elif / else statement
if [ $x -eq 5 ]
then
echo "five"
elif [ $x -eq 7 ]
then
echo "seven"
else
echo "not 5 and not 7"
fi
Comparing numeric using nested if
if [ $x -gt 0 ]
then
if [ $x -lt 10 ]
then
echo "x is greater than 0 but less than 10"
fi
fi
while loop
#!/bin/bash
x=0
while [ $x -lt 10 ]
do
echo $x
let x=$x+1
done
Example - Generate 10 random numbers
i=0
while [ $i -lt 10 ]
do
x=$RANDOM
echo $x
let i=$i+1
done
Example - Infinite loop : interrupting by ctrl+c
#!/bin/sh
while [ 1 ]
do
read x
echo $x
done
for - in loop
#!/bin/sh
for i in "abc" "xyz" 1 2 99
do
echo $i
done
for loop
#!/bin/bash
s=0
for((i=1; i <=n ; i++))
do
let s=$s+$i
done
echo "sum= "$s
case operator for selection of logical branches
Note: End marker of branch indicated by ;;
#!/bin/sh
case "$str" in
abc) echo "string = abc"
;;
xyz) echo "string = xyz"
;;
*) echo "not abc, not zyz"
;;
esac
exit operator
#!/bin/sh
while [ 1 ]
do
read x
echo $x
if [ $x -eq 0 ]
then
echo "script done ..."
exit 0
fi
done
String comparison
#!/bin/sh
if [ $str = "abc" ]
Strings concatenation
str1="AAAAA"
str2=$str1"BBBB"
str3=$str1$str2
OR
str4=${str1}${str2}
Check if a string is null
if [ $str ]
then
echo "Not empty"
else
echo "Empty"
fi
Length of string
x=`expr length $str`
echo "length= "$x
Insert string to constant string
var="good"
echo "This is $var test"
Get substring from string
#!/bin/bash
str2=${str:2:4}
echo $str2
Substring replacement "abc" to "xyz"
#!/bin/bash
str2=${str1/abc/xyz} # replaces only ones
echo $str2
Search of character 'a' in a string
#!/bin/sh
pos=`expr index $str a`
echo "position of the first 'a' = "$pos
String list counting
#!/bin/sh
for i in aa bb cc dd ee ff gg hh
do
echo $i
done
Functions in script
#!/bin/sh
func() {
echo "Inside function"
}
echo "Calling function..."
func
echo "end of main"
Using variables of main program in function
#!/bin/sh
func() {
echo $var
}
var="test of using global variable"
func
Passing of parameters to function
#!/bin/sh
func() {
echo "inside function"
echo $0 # shell script name
echo $1 # first parameter
echo $2 # second parameter
echo "End of function..."
exit 0
}
func 123 "abc"
Passing variable parameters
#!/bin/bash
func() {
let r=$1*$1
echo $r
}
var=123
func $var
Recursive function - Calculation of factorial
#!/bin/sh
factorial() {
if [ "$1" -gt "1" ]
then
i=`expr $1 - 1`
j=`factorial $i`
k=`expr $1 \* $j`
echo $k
else
echo 1
fi
}
read x
factorial $x
Using the function library
Library file (with name my.lb)
func2() {
echo $1$1
}
func3(){
echo $1$1$1
}
Shell program
#!/bin/sh
./my.lb
var=123
func2 123
func3 123
Command line arguments
#!/bin/sh
echo $0 # script file name
echo $1 # first argument
echo $2 # second argument
echo $3 # third argument
Command line arguments without script name
#!/bin/sh
echo $# # argument number
echo $* # command line
echo $@
Get all files and dir names
#!/bin/sh
echo * # file and dir names of current dir
for i in *
do
echo $i
done
File search from root dir
(File name - parameter from command line)
#!/bin/sh
start=$HOME
date
find $start -name $1 -print
List of all files with extension .txt
#!/bin/sh
echo *.txt
Combine a set of text files in one file use
# script >targetfile.lst , not txt-file !!!
#!/bin/sh
lst=*.txt
for i in $lst
do
echo "------------------------------------------------------"
echo "File "$i
echo "------------------------------------------------------"
cat <$i
done
Create new file and write string to it
# Get file name from command line - variable $1
#!/bin/sh
echo $str >$1
Read textlines from console and add them to file
# Get file name from command line - variable $1
#!/bin/sh
echo "Add strings=?"
str="1"
while [ $str ]
do
read str
echo $str >>$1
done
Read first string from text file
#!/bin/sh
read str <$1
echo $str
Text file reading
# script res.txt
#!/bin/sh
str="1"
while [ $str ]
do
read str
echo $str
echo $str
done
Using Arrays
#!/bin/bash
arr=(aa bb cc dd)
echo ${arr[0]} # curly bracket notation
echo ${arr[1]}
echo ${arr[2]}
echo ${arr[3]}
arr[2]="CCCCCCC" # Assignment to array element
echo ${arr[2]}
Get number of elements in array
#!/bin/bash
arr=(aa bb cc dd)
n=${#arr[@]}
echo $n
Array with filenames of current directory
#!/bin/sh
arr=(*) # * is list of all file and dir names
n=${#arr[@]}
echo "number of files and dirs "$n
echo ${arr[0]}
echo ${arr[1]}
Print all array elements
#!/bin/bash
arr=(aa bb cc dd ee ff gg)
n=${#arr[@]}
i=0
while test $i -lt $n
do
echo ${arr[$i]}
let i=$i+1
done
Dynamic expansion of array
# One array element in reality is pair of its index and value
#!/bin/bash
arr=()
n=${#arr[@]}
echo "number of array elements "$n
arr[0]=a
n=${#arr[@]}
echo "number of array elements "$n
arr[1]=b
n=${#arr[@]}
echo "number of array elements "$n
arr[2]=c
n=${#arr[@]}
echo "number of array elements "$n
arr[10]=h
n=${#arr[@]}
echo "number of array elements "$n
echo ${arr[10]}
echo ${arr[4]} # empty string
echo ${arr[6]} # empty string
Get all array and print it
#!/bin/bash
arr=(aa bb cc dd ee ff gg)
echo ${arr[*]} # all array
echo ${arr[@]:0} # aa bb cc dd ee ff gg
echo ${arr[@]:1} # bb cc dd ee ff gg
echo ${arr[@]:2:3} # cc dd ee
for i in ${arr[*]}
do
echo $i
done
Adding element to array
#!/bin/bash
arr=(aa bb cc dd ee ff gg)
echo ${arr[*]}
arr=( "${arr[@]}" "newElem" ) # from right
echo ${arr[*]}
arr=( "newElem" "${arr[@]}" ) # from left
echo ${arr[*]}
Move last element from array
#!/bin/bash
arr=(aa bb cc dd ee ff gg)
echo ${arr[*]}
unset arr[${#arr[@]}-1] # move last element
echo ${arr[*]}
Copying of array
#!/bin/bash
arr=(aa bb cc dd ee ff gg)
echo ${arr[*]}
arr2=( "${arr[@]}" )
echo ${arr2[*]}
Matching value with pattern
dt="14.12.2009"
echo $dt | grep -q "[0-3][0-9]\.[01][0-9]\.[0-2][0-9][0-9][0-9]"
if [ $? -eq 0 ] ; then
echo "Matched"
else
echo "Not matched"
fi
Iterating through static values
i=1
for day in Mon Tue Wed Thu Fri
do
echo "Weekday $((i++)) : $day"
done
Note: List of values should not be separated by comma and also list should not be enclosed in a double quote.
Using variable instead of List of static values
weekdays="Mon Tue Wed Thu Fri"
for day in $weekdays
Getting list of values from script parameters
./myscript.sh Mon Tue Wed Thu Fri
Don’t specify the keyword “in” followed by any list of values.
i=1
for day
do
echo "Weekday $((i++)) : $day"
done
Loop through files and directories
i=1
cd ~
for item in *
do
echo "Item $((i++)) : $item"
done
Using wildcards specific files or directories
for file in /etc/[abcd]*.conf
Breaking out of loop (Use break in loop)
if [ $i -eq 3 ]; then
break;
fi
Continuing the loop (use continue in loop)
if [ $i -eq 7 -o $i -eq 8 ]; then
echo " (WEEKEND)"
continue;
fi
C-style for loop
for (( i=1; i <= 5; i++ ))
do
echo "Number : $i"
done
Infinite C style for loop
for (( ; ; ))
Using comma in C-style for loop
for ((i=1, j=10; i <= 5 ; i++, j=j+5))
do
echo "Number $i: $j"
done
Range of numbers in for-in loop
for num in {1..10}
do
echo "Number: $num"
done
Range of numbers with increments
for num in {1..10..2}
Conditions using test (2 syntax)
test expression
OR
[ expression ]
Checking files
if file is a directory [ -d file ]
if file exists [ -e file ]
if file exists and is a regular file [ -f file ]
if file is a symbolic link [ -L file ]
if file is a file readable by you [ -r file ]
if file is a file writable by you [ -w file ]
if file is a file executable by you [ -x file ]
if file1 is newer than (according to modification time) file2 [ file1 -nt file2 ]
if file1 is older than file2 [ file1 -ot file2 ]
Checking strings
if string is empty [ -z string ]
if string is not empty [ -n string ]
if string1 equals string2 [ string1 = string2 ]
if string1 does not equal string2 [ string1 != string2 ]
Checking if the current user is root
if [ $(id -u) = "0" ]; then
echo "I am root user"
fi
Reading input from keyboard with a prompt message
read -p "Please enter your name : " value1
Note: If you ignore the variable at end, the read command stores value in to system variable $REPLY
read -p "Please enter a value"
No comments:
Post a Comment
Note: only a member of this blog may post a comment.