BASH编程

bash脚本军规

  1. 脚本以shebang开头。例如:

    #!/bin/bash
    
  2. shebang下面紧跟一行注释,表示脚本的用途,例如:

    # This script creates a backup of every MySQL database on the system. 
    
  3. 下面紧跟全局变量声明,并赋值:

    DEBUG=true 
    HTML_DIR=/var/www 
    
  4. 函数应该注意使用局部变量,例如:

    local GREETING="Hello!" 
    
  5. 所有函数声明放到上半部分,shell主体应该在函数的下面

  6. 脚本退出应该有明确的exit status, 例如:

    exit 0 
    

模板如下:

#!/bin/bash 
# 
# <Replace with the description and/or purpose of this shell script.> 
 
GLOBAL_VAR1="one" 
GLOBAL_VAR2="two" 
 
function function_one() { 
  local LOCAL_VAR1="one" 
  # <Replace with function code.> 
} 
 
# Main body of the shell script starts here. 
# 
# <Replace with the main commands of your shell script.> 
 
# Exit with an explicit exit status. 
exit 0