我从其他Shell脚本中学到了什么?

作者Fizer Khan是一位Shell脚本迷,他对有关Shell脚本新奇有趣的东西是如此的痴迷。最近他遇到了authy-ssh脚本,为了缓解ssh服务器双重认证问题,他学到了许多有用且很酷的东西。对此,他想分享给大家。

1. 为输出着色

大多数情况下,你希望输出带颜色的结果,比如绿色代表成功,红色代表失败,黄色代表警告。

  1. NORMAL=$(tput sgr0)
  2. GREEN=$(tput setaf 2; tput bold)
  3. YELLOW=$(tput setaf 3)
  4. RED=$(tput setaf 1)
  5. function red() {
  6. echo -e "$RED$*$NORMAL"
  7. }
  8. function green() {
  9. echo -e "$GREEN$*$NORMAL"
  10. }
  11. function yellow() {
  12. echo -e "$YELLOW$*$NORMAL"
  13. }
  14. # To print success
  15. green "Task has been completed"
  16. # To print error
  17. red "The configuration file does not exist"
  18. # To print warning
  19. yellow "You have to use higher version."

这里使用tput来设置颜色、文本设置并重置到正常颜色。想更多了解tput,请参阅prompt-color-using-tput

2. 输出调试信息

输出调试信息只需调试设置flag。

  1. function debug() {
  2. if [[ $DEBUG ]]
  3. then
  4. echo ">>> $*"
  5. fi
  6. }
  7. # For any debug message
  8. debug "Trying to find config file"

某些极客还会提供在线调试功能:

  1. # From cool geeks at hacker news
  2. function debug() { ((DEBUG)) && echo ">>> $*"; }
  3. function debug() { [ "$DEBUG" ] && echo ">>> $*"; }

3. 检查特定可执行的文件是否存在

  1. OK=0
  2. FAIL=1
  3. function require_curl() {
  4. which curl &>/dev/null
  5. if [ $? -eq 0 ]
  6. then
  7. return $OK
  8. fi
  9. return $FAIL
  10. }

这里使用which来命令查找可执行的curl 路径。如果成功,那么可执行的文件存在,反之则不存在。将&>/dev/null设置在输出流中,错误流会显示to /dev/null (这就意味着在控制板上没有任何东西可打印)。

有些极客会建议直接通过返回which来返回代码。

  1. # From cool geeks at hacker news
  2. function require_curl() { which "curl" &>/dev/null; }
  3. function require_curl() { which -s "curl"; }

4. 输出脚本Usage

当我开始编写shell 脚本,我会用echo来命令打印已使用的脚本。当有大量的文本在使用时, echo命令会变得凌乱,那么可以利用cat来设置命令。

  1. cat << EOF
  2. Usage: myscript <command> <arguments>
  3. VERSION: 1.0
  4. Available Commands
  5. install - Install package
  6. uninstall - Uninstall package
  7. update - Update package
  8. list - List packages
  9. EOF

这里的<<被称为<<here document,字符串在两个EOF中。

5. 用户配置值vs. 默认值

有时,如果用户没有设置值,那么会使用默认值。

  1. URL=${URL:-http://localhost:8080}

检查URL环境变量。如果不存在,可指定为localhost。

6. 检查字符串长度

  1. if [ ${#authy_api_key} != 32 ]
  2. then
  3. red "you have entered a wrong API key"
  4. return $FAIL
  5. fi

利用 ${#VARIABLE_NAME} 定义变量值的长度。

7. 读取超时输入

  1. READ_TIMEOUT=60
  2. read -t "$READ_TIMEOUT" input
  3. # if you do not want quotes, then escape it
  4. input=$(sed "s/[;\`\"\$\' ]//g" <<< $input)
  5. # For reading number, then you can escape other characters
  6. input=$(sed 's/[^0-9]*//g' <<< $input)

8. 获取目录名和文件名

  1. # To find base directory
  2. APP_ROOT=`dirname "$0"`
  3. # To find the file name
  4. filename=`basename "$filepath"`
  5. # To find the file name without extension
  6. filename=`basename "$filepath" .html`

英文出自:FizerKhan

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓