Shell Script Best Practices
Shell Script Best Practices:
1.Constant variables or environment variables name should be UPPER-CASE
2. Changeable variables name should be lower-case
3. Variables in function should be named “_xxx_xx”, starting with underscore “_” to avoid conflict with global variables
4. Use ${xxx} to reference variable, don’t omit {}
5. Code Indent
6. Shell function
Treat shell function as real function, and avoid to use global variables
Try to put similar functions into a file, and write the test script to do function test
Use return/echo to return integer from function, use echo to return string from function and use exit if you want the program to abort
The function name should be end with “_func”
7. Comments
File header comments should contain description, usage[optional], author, create/change date
Line comments – leading line commends or end line comments
Sections comments: comments for a block code just like line comments
Function comments: should contain description/input parameters/return value
8. Make sure the script can be started under any directory(this means you should not assume you script will be started as ./your-script.sh)
9. Empty string test, using ” to quota variable
10. Script argument check
If your script has less than 3 arguments, you can use argument position to check and get argument
If your script has many options to set, use getopts
11. Code sequence in shell script: Global variables —> Shell functions –> Main shell script
Comments
Post a Comment