Learn Bash by Example
All about redirection
to file
stderr to stdout
stderr and stdout 2 file
stdout to stderr
ls -l > ls-l.txt
ls not_exist_file 2> &1
grep for 1>&2
rm -f $(find / -name core_hello) &> /dev/null
Pipes
simple pipe with sed
ls -l | sed -e "s/[aeio]/u/g"
an alternative to ls -l *.txt
ls -l | grep "\.txt$"
Conditionals
Dry Theory
if expression then statement1 else statement2
if expression1 then statement1 else if expression2 then statement2 else statement3
Conditionals with variables
T1="foo"
T2="bar"
if [ "$T1" = "$T2" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
Variable
using variables
STR="Hello World!"
echo $STR
simple backup script
OF=/var/my-backup-$(date +%Y%m%d).tgz
tar -zcvf $OF /home/me/
HELLO=Hello
function hello {
local HELLO=World
echo $HELLO
}
echo $HELLO
hello
echo $HELLO
local variables
Loops for, while and until
Numeric ranges
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
bash v3.0+ has inbuilt support for setting up ranges
for i in {1..5}
do
echo "Welcome $i times"
done
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
do
echo "Welcome $i times"
done
Bash v4.0+ support {START..END..INCREMENT}
Three expression bash for loops syntax
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times"
done
Conditional exit with break
for I in 1 2 3 4 5
do
statements1
statements2
if (disaster-condition)
then
break #Abandon the loop.
fi
statements3 #While good and, no disaster-condition.
done
While example
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
Until example
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
Functions
Functions sample
function hello {
echo Hello!
}
hello
Functions with parameters
function e {
echo $1
}
e Hello
Comparison Operators
integer comparison
-lt (<)
-gt (>)
-le (<=)
-ge (>=)
-eq (==)
-ne (!=)
string comparison
s1 = s2
s1 != s2
s1 < s2
s1 > s2
find number which can be divided by 7
for i in {1..100..1};
do let j=$i%7 ;
if [ $j -eq 0 ] ;
then echo $i;
fi;
done;
Userful command
wc (counts lines, words and bytes)
wc -w -l -c vimtest.txt
grep (print lines matching a search pattern)
grep "hello" vimtest.txt -c
sed (stream editor)
sed 's/to_be_replaced/replaced/g' vimtest.txt
sed '2,5d' vimtest.txt
User interface
Using select to make simple menus
#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done
Test if the program has received an argument
#!/bin/bash
if [ -z "$1" ]; then
echo usage: $0 directory
exit
fi
Misc
Reading user input with read
read NAME
echo "Hi $NAME!"
Arithmetic evaluation
echo $((1+1))
echo $[1+1]
Getting the return value
$?
Debugging
Ways Calling BASH
#!/bin/bash
set -ex
Learn Bash by example
By jingliu
Learn Bash by example
- 585