I've been writing quite a large amount of shell scripts for the past few days. Here's are some tips that might be of help.
1. debugging
The simplest way to step through the execution of your shell script is to provide it with the -x option. For example: sh -x myscript.sh
2. array
Yes, shell script can do them. To create an array:
foo=("apple" "orange" "lemon" "durian")
Another example of creating an array automatically:
NETDEVICES="$(cat /proc/net/dev | awk -F: '/[0-9]:/{print $1}')"
To iterate through the array, a for loop will do:
for DEV in $NETDEVICES; do
echo -n "$DEV"
done
3. printing a specific line from a file
This is a simple
head and
tail trick:
1st line: cat file.txt | head -n1
2nd line: cat file.txt | head -n2 | tail -n1
3rd line: cat file.txt | head -n3 | tail -n1
and so on...
4. maths
a=1
b=2
c=$(( $a + $b))
shell script however, does not support decimals. For this, I use awk with printf:
a=1.1
b=2.2
c=$(echo $a $b | awk '{printf("%s", ($1+$2))}')
5. string concatenation
a="takizo"
b="memang"
c="handsome"
d=$a" "$b" "$c
or
a="takizo"
b="memang"
c="handsome"
d=${a}" "${b}" "${c}
6. manipulating IFS
IFS stands for internal field separator (or something like that). Example:
a="paul|memang|handsome"
IFS="|"
echo $a
This will replace the IFS with spaces. Of course, for the above, you can use awk:
a="paul|memang|handsome"
echo $a | awk -F | '{ printf("%s %s %s", $1, $2, $3) }'
7. return codes
use $?. Example:
cat /etc/passwd
echo $?
cat /etc/password
echo $?
8. other shell special vars
These are also good for debugging. Try them out for yourself too see what they actually output. Example:
#!/bin/sh
echo "ARG: $1 $2 $3 $4"
echo "script name: $0"
echo "num args: $#"
echo "pid: $$"
echo "options: $-"
echo "args: $*"
echo "args: $@"
echo $?