电脑技术学习

对话 UNIX: 更多 shell 脚本技术

dn001

  如果您有比较丰富的 shell 脚本编程经验,可能能够读懂这个脚本。但是,脚本编程的初学者很难理解这个函数的作用。如果花上几分钟在这个脚本中添加注释,情况就大不一样了。清单 7 给出包含注释的同一个函数。

  清单 7. 包含注释的脚本示例

#########################################
# function confirm_and_exit
#########################################
confirm_and_exit() {
 # if the debug level is set to 3 or higher, send every evaluated line to stdout
 [[ ${_DEBUG_LEVEL} -ge 3 ]] && set –x
 # Continue to prompt the user until they provide a valid answer
 while [[ -z ${_EXIT_ANS} ]]
 do
  # prompt user if they want to exit the script
  # cup_echo function calls tput cup <x> <y>
  # syntax:
  # cup_echo <string to display> <row on stdout to display>
    <column on stdout to display>
  cup_echo "Are you sure you want to exit? [Y/N] 
    c" ${_PROMPT_ERR_ROW} ${_PROMPT_ERR_COL}
  # change cursor to normal via tput
  ${_TPUT_CMD} cnorm
  # read value entered by user
  # if _NO_EOL_FLAG is supplIEd, use value of _READ_FLAG or “-n
  # if _NO_EOL_FLAG is supplied, use value as characters aloud on read
  # assign value entered by user to variable _EXIT_ANS
  read ${_NO_EOL_FLAG:+${_READ_FLAG:-'-n'}} ${_NO_EOL_FLAG} _EXIT_ANS
  # change cursor to invisible via tput
  ${_TPUT_CMD} civis
 done
 # if user entered “n, return to previous block of code with return code 0
 # if user entered “y, exit the script
 # if user entered anything else, execute function invalid_selection
 case ${_EXIT_ANS} in
  [Nn]) unset _EXIT_ANS; return 0;;
  [Yy]) exit_msg 0 1 "Exiting Script";;
    *) invalid_selection ${_EXIT_ANS}; unset _EXIT_ANS;;
 esac
 # exit function with return code 0
 return 0
}

标签: