我從其他Shell指令碼中學到了什麼?

csdn發表於2013-08-15

  作者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`

  英文來源:What-I-learned-from-other-s-shell-scripts

相關文章