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”


  • 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 ./

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

If You need more visit our site –



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s