`bash set -u # The script crashes if a variable is uninitialized set -e # The script crashes if the exit code of a command is not zero
`
- Use
"$@"
instead of$@
- Use quotes around filenames
- Use
mkdir -p
to create a full path - Use
rm || true
to avoid a non-zero exit - Use traps when using temporary files:
`bash if [ ! -e $lockfile ]; then trap "rm -f $lockfile; exit" INT TERM EXIT touch $lockfile critical-section rm $lockfile trap - INT TERM EXIT else echo "critical-section is already running" fi
` - To avoid race conditions with lock files:
`bash if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; then
` - Implement rollback functions when modifying dangerous things:
`bash rollback() { del_from_passwd $user if [ -e /home/$user ]; then rm -rf /home/$user fi exit } trap rollback INT TERM EXIT add_to_passwd $user cp -a /etc/skel /home/$user chown $user /home/$user -R trap - INT TERM EXIT
` - Be atomic : work on copies and if the work succeeded, copy the modified files back
- Never use [ or test, always use [[ for secure string handling
- [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells
- Avoid using echo and use printf instead