從Shell指令碼中學到的知識

來源:互聯網
上載者:User

作者Fizer Khan是一位Shell指令碼迷,他對有關Shell指令碼新奇有趣的東西是如此的癡迷。最近他遇到了authy-ssh指令碼,為了緩解ssh伺服器雙重認證問題,他學到了許多有用且很酷的東西。對此,他想分享給大家。

1.  為輸出著色

大多數情況下,你希望輸出帶顏色的結果,比如綠色代表成功,紅色代表失敗,黃色代表警告。

Shell代碼

 
  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. function green() { 
  8. echo -e "$GREEN$*$NORMAL" 
  9. function yellow() { 
  10. echo -e "$YELLOW$*$NORMAL" 
  11. # To print success 
  12. green "Task has been completed" 
  13. # To print error 
  14. red "The configuration file does not exist" 
  15. # To print warning 
  16. yellow "You have to use higher version." 

這裡使用tput來設定顏色、文本設定並重設到正常顏色。想更多瞭解tput,請參閱prompt-color-using-tput。

2.  輸出調試資訊

輸出調試資訊只需調試設定flag。

Shell代碼

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

某些極客還會提供線上調試功能:

Shell代碼

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

3.  檢查特定可執行檔檔案是否存在?

Shell代碼

 
  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 

這裡使用which來命令尋找可執行檔curl 路徑。如果成功,那麼可執行檔檔案存在,反之則不存在。將&>/dev/null設定在輸出資料流中,錯誤流會顯示to /dev/null 這就意味著在控制板上沒有任何東西可列印)。

有些極客會建議直接通過返回which來傳回碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.