#!
/bin/bash
Basics
1
Index
Integers
Conditional statements (if, case)
Loops (for do done, until do done, while do done)
Arithmetic Operators (working with numbers)
Arithmetic Conditional Operators(comparing numbers)
String Comparison Operators(comparing text)
File Testing Operators
Boolean Operators
2
Integers
Integers
Integer = 0,1,2,3,4,…
No letters or other characters
Needs to be declared in the beginning of your script
declare –i my_var=5
The '-i' option is used to make variable 'my_var' have the integer attribute.
In other words, declare variable 'myvar' as the integer.
4
Integers
#!/bin/bash #!/bin/bash
declare -i y=10 declare -i y=10
declare -i number=0 declare -i number=0
declare -i sum=0 declare -i sum=0
read number read number 11
read numbery read numbery 12
read numberz read numberz 13
21 25
sum=$y+$number sum=$((y + number))
sum2=$numbery+$numberz sum2=$((numbery + numberz))
echo $sum $sum2 echo $sum $sum2
5
Conditional statements
Overview
Syntax Description
Test a condition and execute the then clause if
if then fi
it is true
Execute the then clause if the condition is true,
if then else fi
otherwise execute the else clause
Test multiple conditions and execute whichever
if then elif else fi
clause is true
case Based on a list
if then else fi
#!/bin/bash
if [<test-command>]
then if [ $1 -eq $2 ]; then
do something (test-command is true) echo "they are equal"
else else
do something else (test-command is NOT true) echo "they are NOT equal"
fi fi
“If test-commando is true then we do something, if NOT true we do
something else”
8
[] is a synonym for the command test
[Link] check “man test”
Spaces are very important because ‘[‘ is interpreted as a command just like e.g. ‘ls’, ‘cat’, …
so ‘[$#’ won’t work just as ls/ makes no sense
What is the difference between test, [ and [[ ?
[Link]
#!/bin/bash
See previous slide to compare test with [
n=1
[[ is a new, improved version of [
while [ $n -le 5 ]
This makes it easier to use, as shown in the link. do
echo "welcome $n "
TIP1: To be backwards compatible use [ n=$((n+1))
done
TIP2: [[ is used for strings and files.
If you want to compare numbers, use an ArithmeticExpression (( ))
#!/bin/bash #!/bin/bash
read naam n=1
echo naam
while (( $n <= 5 ))
if [[ $naam == *A* ]]; do
then echo "welcome $n "
echo "welcome $naam, containing A" n=$((n+1))
fi done
What if you want both “A” and “a” to give a match?
if then elif else fi
if condition
then
#!/bin/bash
do something
elif condition 2 if [ $1 -eq $2 ]; then
then echo "they are equal"
do something elif [ $1 -gt $2 ]; then
elif condition n echo "first is greater than second"
elif [ $1 -lt $2 ]; then
then echo "first is smaller than second"
do something fi
else
none of the above is true
fi
11
Case examples
#!/bin/bash ubuntuserver:~/$ date
Wed Oct 26 [Link] UTC 2022
day=$(date +"%a")
ubuntuserver:~/$ date +"%a"
case $day in Wed
Mon | Tue | Wed | Thu | Fri)
echo "today is a weekday" #!/bin/bash
;;
read naam
Sat | Sun) echo $naam
echo "today is the weekend"
;; case "$string" in
*A*)
*) echo "Contains A"
echo "date not recognized" ;;
;; *)
echo "Does not contain A"
esac ;;
esac
12
Loops
Overview
Syntax Description
Continue to loop for a predetermined
for do done
(vooraf gekend) number of lines, files, etc
Continue to loop as long as a certain
while do done
condition is true
Continue to loop until a certain condition
until do done
is met
For Loop
for i in 1 2 3 4 5
do
echo “Welcome $i times”
done
Continue to loop for a predetermined number of lines, files, etc
Prints:
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
15
For Loop with range {..}
for i in {1..5}
do
echo “Welcome $i times”
done
Prints:
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
16
For Loop with step values (only bash
4.0+)
for i in {0..10..2}
do
echo “Welcome $i Times”
done
Prints: How to check bash version?
Welcome 0 times
Welcome 2 times bash --version
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times
17
For loop with strings
for car in mazda toyota honda bmw ford
do
echo "Value of car is: $car"
done
Prints:
Value of car is: mazda
Value of car is: toyota
Value of car is: honda
Value of car is: bmw
Value of car is: ford
18
For loop with command output
for i in $(ls /tmp/*)
do
echo “File $i”
done
Prints:
File xxx
File yyy
…
19
While loop
declare -i i=0 declare -i i=0
while [[ $i < 5 ]] while [ $i -lt 5 ]
do do
echo $i echo $i
((i++)) ((i++))
done done
Continue to loop as long as a certain condition is true
Prints:
0
1
2
3
4
20
Until
declare -i i=0 declare -i i=0
until [[ $i > 5 ]] until [ $i -gt 5 ]
do do
echo $i echo $i
((i++)) ((i++))
done done
Continue to loop until a certain condition is met
Prints:
0
1
2
3
4
5
21
Arithmetic Operators
ARITHMETIC OPERATORS
Arithmetic operators in Bash give us the ability to do things like addition,
subtraction, multiplication, division, and other basic arithmetic inside of a Bash
script.
Syntax Description
+ Addition
Sum=$((10+3))
- Subtraction echo "Sum = $Sum"
* Multiplication
/ Division (deling)
% Modulus (rest bij deling)
** Raise to a power (machten)
((i++)) Increment a variable
((i--)) Decrement a variable
Arithmetic Conditional
Operators
(Comparisons)
Comparisons (vergelijken)
Arithmetic conditional operators are usually used on two numbers to determine if
a certain condition is true or false.
Less than -lt <
Greater than -gt >
Less than or equal to -le <=
Greater than or equal to -ge >=
Equal -eq ==
Not equal -ne !=
left column : single brackets [ ] or double brackets [[ ]],
right column : only with double brackets.
Best choose for [ ]
String Operators
Comparing strings
We can use string comparison operators to determine if a string is empty or not,
and to check if a string is equal, less, or greater to another string.
#!/bin/bash
= equal a="apple"
b="banana"
!= not equal
if [[ "$a" < "$b" ]]; then
< less then (lexicographically) echo "a is less than b"
fi
> greater then (lexicographically)
-n string1 string1 is not empty if [[ "$a" != "$b" ]]; then
echo "a is NOT equal to b"
-z string2 string2 is empty fi
sve@hp-lnx-sve:~/scripts$ ./[Link]
a is less than b
a is NOT equal to b
Substr: get part of string
#!/bin/bash
In the example, the value, 6 indicates the
starting point from where the substring Str="Learn Linux from Stefan Verbruggen"
subStr=${Str:6:5}
will start and 5 indicates the length of the echo $subStr
substring.
sve@hp-lnx-sve:~/scripts$ ./[Link]
Linux
sve@hp-lnx-sve:~/scripts$
${#str} get length of string
#!/bin/bash
str=”Linux for ever”
echo "${#str}"
sve@hp-lnx-sve:~/scripts$ ./[Link]
14
sve@hp-lnx-sve:~/scripts$
File Testing Operators
File/Directory testing
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-r filename Check if file is a readable
-w filename Check if file is writable
-x filename Check if file is executable
Boolean Operators
OPERANDS (man test)
Boolean operators include and &&, or || and not equal to !. These operators allow us to test if two or more conditions are true or not.
Syntax Description
&& Logical AND operator
|| Logical OR operator
! NOT equal to operator
Testing if file exists on filesystem
files=“/etc/passwd /etc/group /etc/schadow /etc/gshadow”
for f in $files
do
[ -f $f ] && echo “$f file found” || echo “*** ERROR - $f file is missing”
done
Prints:
/etc/passwd file found
/etc/group file found
ERROR /etc/schadow file is missing
/etc/gshadow file found
Piping and Redirection
PIPING AND REDIRECTION
Piping: sending stdout from one command to stdin of another
command:
cat [Link] | grep “searchterm”
Redirection output to file
python [Link] > [Link] # stdout to (file)
python [Link] >> [Link] # stdout to (file), append
python [Link] 2> [Link] # stderr to (file)
python [Link] 2>&1 # stderr to stdout
python [Link] 2>/dev/null # stderr to (null)
python [Link] &>/dev/null # stdout and stderr to (null)
python [Link] < [Link] # feed [Link] to stdin for python
PIPING TO SCRIPT
Each process gets 3 files for piping purposes:
STDIN - /proc/<processID>/fd/0
STDOUT - /proc/<processID>/fd/1
STDERR - /proc/<processID>/fd/2
Shortcuts:
STDIN - /dev/stdin or /proc/self/fd/0
STDOUT - /dev/stdout or /proc/self/fd/1
STDERR - /dev/stderr or /proc/self/fd/2
PIPING TO SCRIPT
Look for cheat sheets
TIP
[Link]
Thanks!
TomVan Den Broeck
tomvdb@[Link]
Translation and additions/updates
[Link]@[Link]
41