Ref- http://www.ramil.pro/2013/01/bash.html
1) If condition
There are 3 options:1) if..then..else..fi
2) [ condition ] && ( expression-if-true ) || ( expression-if-false )
3) test condition && expression-if-true || expression-if-false
2) Loops
1) Standard for..infor arg in list;
do
commands
done
2) C-like for (attention! double brackets!)
for (( i=1; i <= 10; i++ ));
do
commands
done
3) While loop
while [ condition ];
do
commands
done
or
while (( C-like condition ));
do
commands
done
4) Until loop
until [ condition ];
do
commands
done
break [N] - exit the loop
continue [N] - start over
Example:
for (( j=0; j<3 -gt="" arr="" code="" do="" done="" fi="" for="" i="" if="" j="" then="" tmp="">3>
3) Functions
function function_name {
commands
}
or
function_name() {
commands
}
exit and return just work as usually
4) Arrays
declare -a array - declare the array first
define value:
a[13] = "foo"
retrieve value:
${a[13]} - only this way!
5) Strings
String length:str="string"
len=${#str}
Substring:
${str:pos}
${str:pos:len}
Remove part of string:
${str#substring} - remove the shortest part from the beginning
${str##substring} - remove the longest part from the beginning
${str%substring} - remove the shortest part from the end
${str%%substring} - remove the shortest part from the end
Replacement:
${str#substring/replacement} - from the beginning
${str%substring/replacement} - from the end
6) case..in..esac
case $variable in
condition 1)
actions
;;
condition 2)
actions
;;
esac
7) I/O
Read the input:read -p "Input string: " str
echo $str
8) Features
$@ - arguments array$1, $2, $n - arguments in order
$0 - program (self) name
$# - arguments number
$* - all arguments as one sting
$_ - last argument of the last command
$? - previous command return code
$$ - own PID
$! - PID of the last background process
!! - previous command as a string
(( a += 1 )) - double brackets let us code like C
$RANDOM - returns a pseudorandom value within 0..32767
declare -r constant - declare as read-only
declare -a - declare as array
declare -i - declare as integer