Advanced Bash-Scripting HOWTO: A guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 3. Tutorial / Reference | Next |
Turandot: Gli enigmi sono tre, la morte una! Caleph: No, no! Gli enigmi sono tre, una la vita! | |
Puccini |
Assigning reserved words or characters to variable names.
1 var1=case 2 # Causes problems. 3 var2=23skidoo 4 # Also problems. Variable names starting with a digit are reserved by the shell. 5 # Try var2=_23skidoo. Starting variables with an underscore is o.k. 6 var3=xyz((!* 7 # Causes even worse problems. |
Using a hyphen or other reserved characters in a variable name.
1 var-1=23 2 # Use 'var_1' instead. |
Using white space inappropriately (in contrast to other programming languages bash can be finicky about white space).
1 var1 = 23 2 # 'var1=23' is correct. 3 let c = $a - $b 4 # 'let c=$a-$b' or 'let "c = $a - $b"' are correct. 5 if [ $a -le 5] 6 # 'if [ $a -le 5 ]' is correct. |
Using uninitialized variables (that is, using variables before a value is assigned to them). An uninitialized variable has a value of "null", not zero.
Mixing up = and -eq in a test. Remember, = is for comparing literal variables and -eq is for numbers.
1 if [ $a = 273 ] # Wrong! 2 if [ $a -eq 273 ] # Correct. 3 |
Sometimes variables within "test" brackets ([ ]) need to be quoted (double quotes). Failure to do so may cause unexpected behavior. See Example 3-13, Example 3-73, and Example 3-17.
Commands issued from a script may fail to execute because the script owner lacks execute permission for them. If a user cannot invoke a command from the command line, then putting it into a script will likewise fail. Try changing the attributes of the command in question, perhaps setting the suid bit (as root, of course).
Using bash version 2 functionality (see below) in a script headed with #!/bin/bash may cause a bailout with error messages. Your system may still have an older version of bash as the default installation (echo $BASH_VERSION). Try changing the header of the script to #!/bin/bash2.
A script may not export variables back to its parent process, the shell, or to the environment. Just as we learned in biology, a child process can inherit from a parent, but not vice versa.
1 WHATEVER=/home/bozo 2 export WHATEVER 3 exit 0 |
bash$ echo $WHATEVER bash$ |
Making scripts "suid" is generally a bad idea, as it may compromise system security. Administrative scripts should be run by root, not regular users.
Using shell scripts for CGI programming may be problematic. Shell script variables are not "typesafe", and this can cause undesirable behavior as far as CGI is concerned. Moreover, it is difficult to "hacker-proof" shell scripts.