Conventions and best practices are to avoid inventing new syntax to make it "look better". Don't do that. Every time I've done that I've come to regret it when it fails to translate to some other shell.
Never paste shell code into a word processor. It will convert all your quote characters into nasty smart quote characters which to the shell don't count as quotes at all.
Arithmetic is best done inside RESULT=$((VAR+37))
statements instead of archaic let
statements.
Numerical comparisons are best done inside if (( VAR1 > VAR2 ))
statements instead of the archaic if [ "$VAR1" -gt "$VAR2" ]
String comparisons are still done inside if [[ "$STR" == "$STR2" ]]
statements, note the doubled [[ ]]. The single [ ] mostly work the same but are archaic.
Backticks a la VAR=`command`
are also archaic. To capture the output of a command, use VAR=$(command)
instead.
Never use the $?
special variable if you can possibly help it. If you're trying to use it, there's probably a logic structure that would work better, such as if
, while
, or case
.
You can always plug a command into an if/while statement where you'd put a ((math)) or [[ bracket ]] statement, because to the shell they're mostly the same thing. case is different, case operates on a string.
Whitespace is unimportant inside (( )) brackets, but anywhere else, whitespace is crucial. This is wrong:
VAR = "value"
This is right:
VAR="value"
Single quotes ' and double-quotes " can both be used to denote strings but operate differently. Any text inside single quotes is not evaluated, where text inside double-quotes has variables substituted inside.
If you manage to force quote characters to be stored in a variable, they are not processed specially by the shell any more, they're just characters.
Avoid making too-long command | command | command | command | command
chains. They are inefficient.
Avoid using external commands to process single strings, like VAR=$(echo "a b c" | awk '{ print $1 }')
There's usually a shell builtin that will do a better job without the overhead of making an entire external program / language load, process, print, and quit.
The advanced bash programming guide is a good place to look things up since nobody really had everything memorized.