对于这么小的函数,这似乎太麻烦了,甚至有点过分,但是对于 shell 脚本编程新手和阅读这个函数的人员而言,注释是非常有价值的。
在 shell 脚本中,注释的另一个极其有帮助的用途是,解释变量的有效值以及解释返回码的含义。
清单 8 中的示例取自一个 shell 脚本的开头。
清单 8. 未加注释的变量示例
#!/usr/bin/bash
trap 'exit_msg 1 0 "Signal Caught. Exiting..."' HUP INT QUIT KILL ABRT
trap 'window_size_changed' WINCH
_MSG_SLEEP_TIME=3
_RETNUM_SIZE=6
_DEBUG_LEVEL=0
_TMPDIR="/tmp"
_SP_LOG="${0##*/}.log"
_SP_REQUESTS="${HOME}/sp_requests"
_MENU_ITEMS=15
LESS="-P LINE: %l"
export _SP_REQUESTS _TMPDIR _SP_LOG _DB_BACKUP_DIR
export _DEBUG_LEVEL _NEW_RMSYNC _RMTOTS_OFFSET_COL
同样,很难理解 trap 语句的作用以及每个变量可以是哪些值。除非把整个脚本都读一遍,否则不可能看出这些变量的意义。另外,这里没有提到这个脚本中使用的任何返回码。这会大大增加解决 shell 脚本问题的难度。向 清单 8 的代码行中添加一些注释和一个专门描述返回码的注释块,这样就可以显著降低理解难度。看看下面的清单 9。
清单 9. 带注释的变量示例
#!/usr/bin/bash
#########################################################################
# traps
#########################################################################
# trap when a user is attempting to leave the script
trap 'exit_msg 1 0 "Signal Caught. Exiting..."' HUP INT QUIT KILL ABRT
trap 'window_size_changed' WINCH # trap when a user has resized the window
#########################################################################
#########################################################################
# defined/exported variables
#########################################################################
_MSG_SLEEP_TIME=3 # seconds to sleep for all messages
# (if not defined, default will is 1 second)
_CUSTNUM_SIZE=6 # length of a customer number in this location
# (if not defined, default is 6)
_DEBUG_LEVEL=0 # log debug messages. log level is accumulative
# (i.e. 1 = 1, 2 = 1 & 2, 3 = 1, 2, & 3)
# (if not defined, default is 0)
# Log levels:
# 0 = No messages
# 1 = brIEf messages (start script, errors, etc)
# 2 = environment setup (set / env)
# 3 = set -x (A LOT of spam)
_TMPDIR="/tmp" # Directory to put work/tmp files
# (if not defined, default is /tmp)
_SP_LOG="${0##*/}.log" # log of script events
_SP_REQUESTS="${HOME}/sp_requests"
# file to customer record requests,
# also read at startup
_MENU_ITEMS=15 # default number of items to display per page
# (it not defined, default is 10)
LESS="-P LINE: %l" # format 'less' prompt. MAN less if more info
# export the variables defined above
export _MSG_SLEEP_TIME _CUSTNUM_SIZE _DEBUG_LEVEL _TMPDIR
_SP_LOG _SP_REQUESTS _MENU_ITEMS
#########################################################################
标签: