從Shell腳本中學到的知識
作者Fizer Khan是一位Shell腳本迷,他對有關(guān)Shell腳本新奇有趣的東西是如此的癡迷。最近他遇到了authy-ssh腳本,為了緩解ssh服務(wù)器雙重認證問題,他學到了許多有用且很酷的東西。對此,他想分享給大家。
1. 為輸出著色
大多數(shù)情況下,你希望輸出帶顏色的結(jié)果,比如綠色代表成功,紅色代表失敗,黃色代表警告。
Shell代碼
- NORMAL=$(tput sgr0)
 - GREEN=$(tput setaf 2; tput bold)
 - YELLOW=$(tput setaf 3)
 - RED=$(tput setaf 1)
 - function red() {
 - echo -e "$RED$*$NORMAL"
 - }
 - function green() {
 - echo -e "$GREEN$*$NORMAL"
 - }
 - function yellow() {
 - echo -e "$YELLOW$*$NORMAL"
 - }
 - # To print success
 - green "Task has been completed"
 - # To print error
 - red "The configuration file does not exist"
 - # To print warning
 - yellow "You have to use higher version."
 
這里使用tput來設(shè)置顏色、文本設(shè)置并重置到正常顏色。想更多了解tput,請參閱prompt-color-using-tput。
2. 輸出調(diào)試信息
輸出調(diào)試信息只需調(diào)試設(shè)置flag。
Shell代碼
- function debug() {
 - if [[ $DEBUG ]]
 - then
 - echo ">>> $*"
 - fi
 - }
 - # For any debug message
 - debug "Trying to find config file"
 
某些極客還會提供在線調(diào)試功能:
Shell代碼
- # From cool geeks at hacker news
 - function debug() { ((DEBUG)) && echo ">>> $*"; }
 - function debug() { [ "$DEBUG" ] && echo ">>> $*"; }
 
3. 檢查特定可執(zhí)行的文件是否存在?
Shell代碼
- OK=0
 - FAIL=1
 - function require_curl() {
 - which curl &>/dev/null
 - if [ $? -eq 0 ]
 - then
 - return $OK
 - fi
 - return $FAIL
 - }
 
這里使用which來命令查找可執(zhí)行的curl 路徑。如果成功,那么可執(zhí)行的文件存在,反之則不存在。將&>/dev/null設(shè)置在輸出流中,錯誤流會顯示to /dev/null (這就意味著在控制板上沒有任何東西可打?。?。
有些極客會建議直接通過返回which來返回代碼。















 
 
 






 
 
 
 