Shell Script Standards

推荐看看 https://google.github.io/styleguide/shellguide.html

Part1: 命名约定
  • 本文档的命名约定是系统配置文件、脚本文件;
  • 文件名、变量名、函数名不超过20个字符;
  • 命名只能使用英文字母,数字和下划线,只有一个英文单词时使用全拼,有多个单词时,使用下划线分隔,长度较长时,可以取单词前3~4个字母。
  • 文件名全部以小写命名,不能大小写混用(通过U盘交换文件时,大小写可能会丢失,即:大写文件名可能会全部变成小写文件名);
  • 避免使用Linux的保留字如true、关键字如PWD等(见附表);
  • 从配置文件导出配置时,要注意过滤空行和注释
Part2: 代码开头约定
  • 第一行一般为调用使用的语言
  • 下面要有这个程序名,避免更改文件名为无法找到正确的文件
  • 版本号
  • 更改后的时间
  • 作者相关信息
  • 该程序的作用,及注意事项
  • 版权与是否开放共享GNU说明
  • 最后是各版本的更新简要说明

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
# -------------------------------------------------------------------------------
# Filename: check_mem.sh
# Revision: 1.1
# Date: 2019/02/10
# Author: xiaoming
# Email: xiaoming#gmail.com
# Description: Plugin to monitor the memory of the system
# Notes: This plugin uses the "" command
# -------------------------------------------------------------------------------
# Copyright: 2009 (c) xiaoming
# License: GPL
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# you should have received a copy of the GNU General Public License
# along with this program (or with Nagios);
#
# Credits go to Ethan Galstad for coding Nagios
# If any changes are made to this script, please mail me a copy of the changes
# -------------------------------------------------------------------------------
#Version 1.0
#The first one , can monitor the system memory
#Version 1.1
#Modify the method of the script ,more fast

Part3: 环境变量
  • 变量:全部是大写字母
  • 变量引用:全部以变量名加双引号引用,如”$TERMTYPE”,或“${TERMTYPE}”,如果变量类型是数值型不引用,如:
  • 如果需要从配置文件导出变量,则在变量前加一大写字母,以识别导出变量与自定义环境变量的区别,如:
  • 变量值的引用尽量以$开头,如$(ls inst_.sh),避免使用ls inst_。sh
  • 循环控制变量可以命名为单个字母, 比如 i、j等。 也可以是更有意义的名称, 比如 UserIndex。
  • 环境变量和全局变量 在脚本开头定义。
  • 函数中使用较多的文件,以环境变量的形式在文件开头定义,仅函数中使用的变量在函数开头定义
Part4: 脚本的基本结构

一个脚本的基本结构是这样的:

1
2
3
4
5
6
7
8
#!SHEBANG

CONFIGURATION_VARIABLES

FUNCTION_DEFINITIONS

MAIN_CODE
Shebang

More Ref:

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~