Created
September 20, 2015 22:06
-
-
Save scemama/334f729f810ec42391e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment