Scripting
Fundamentals
Shebang (first line of file) for shell (.sh
) files: #!/bin/sh
or #!/bin/bash
Shell arguments: $1
, $2
… $9
; $@
(all arguments)
If Statements
if condition1; then
command1a
command1b
elif condition2; then
command2
else
command3
fi
Conditions
test $# -ne 2
or [ $# -ne 2 ]
(spaces are required!)
Case Statements
echo -n "yes/no? "
read answer
case $answer in
y | yes ) echo "yes";;
n | no ) echo "no";;
*) echo "invalid input";;
esac
Loops
For Loops
for i in a b c; do
echo $i
done
IFS=$'\n' # Internal Field Separator (needed to allow spaces in filenames)
for file in $*; do
cp "$file" "$file.bak"
done
While Loops
i=1
while [ $i -le 5 ]; do
echo $i; i=$(($i+1))
done
Until Loops
i=1
until [ $i -gt 5 ]; do
echo $i; i=$(($i+1))
done
Functions
function myFunc {
echo "Hello World, $1!"
}
myfunc "Linux"
myFunc() {
echo "Hello World, $1!"
}
myfunc "Linux"
greet() {
echo "Hello $1 $2!"
}
greet "John" "Doe"