作者Fizer Khan是一位Shell腳本迷,他對有關Shell腳本新奇有趣的東西是如此的癡迷。最近他遇到了authy-ssh腳本,為了緩解ssh服務器雙重認證問題,他學到了許多有用且很酷的東西。對此,他想分享給大家。
一、Colors your echo
大多數情況下,你希望輸出echo Color,比如綠色代表成功,紅色代表失敗,黃色代表警告。
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來設置顏色、文本設置并重置到正常顏色。想更多了解tput,請參閱prompt-color-using-tput。
二、To print debug information (打印調試信息)
打印調試信息只需調試設置flag。
function debug() { if [[ $DEBUG ]] then echo ">>> $*" fi } # For any debug message debug "Trying to find config file"
某些極客還會提供在線調試功能:
# From cool geeks at hacker news function debug() { ((DEBUG)) && echo ">>> $*"; } function debug() { [ "$DEBUG" ] && echo ">>> $*"; }
三、To check specific executable exists or not (檢查特定可執行的文件是否存在)
OK=0 FAIL=1 function require_curl() { which curl &>/dev/null if [ $? -eq 0 ] then return $OK fi return $FAIL }
這里使用which來命令查找可執行的curl 路徑。如果成功,那么可執行的文件存在,反之則不存在。將&>/dev/null設置在輸出流中,錯誤流會顯示to /dev/null (這就意味著在控制板上沒有任何東西可打印)。
有些極客會建議直接通過返回which來返回代碼。
# From cool geeks at hacker news function require_curl() { which "curl" &>/dev/null; } function require_curl() { which -s "curl"; }
四、To print usage of scripts (打印使用的腳本)
當我開始編寫shell 腳本,我會用echo來命令打印已使用的腳本。當有大量的文本在使用時, echo命令會變得凌亂,那么可以利用cat來設置命令。
cat << EOF Usage: myscript <command> <arguments> VERSION: 1.0 Available Commands install - Install package uninstall - Uninstall package update - Update package list - List packages EOF
這里的<<被稱為<<here document,字符串在兩個EOF中。
五、User configured value vs Default value (用戶配置值VS 默認值)
有時,如果用戶沒有設置值,那么會使用默認值。
URL=${URL:-http://localhost:8080}
檢查URL環境變量。如果不存在,可指定為localhost。
六、To check the length of the string 檢查字符串長度
if [ ${#authy_api_key} != 32 ] then red "you have entered a wrong API key" return $FAIL fi
利用 ${#VARIABLE_NAME} 定義變量值的長度。
七、To read inputs with timeout (讀取輸入超時)
READ_TIMEOUT=60 read -t "$READ_TIMEOUT" input # if you do not want quotes, then escape it input=$(sed "s/[;\`\"\$\' ]//g" <<< $input) # For reading number, then you can escape other characters input=$(sed 's/[^0-9]*//g' <<< $input)
八、To get directory name and file name (獲取目錄名和文件名)
# To find base directory APP_ROOT=`dirname "$0"` # To find the file name filename=`basename "$filepath"` # To find the file name without extension filename=`basename "$filepath" .html`
掃碼二維碼 獲取免費視頻學習資料
- 本文固定鏈接: http://phpxs.com/post/4408/
- 轉載請注明:轉載必須在正文中標注并保留原文鏈接
- 掃碼: 掃上方二維碼獲取免費視頻資料