Shell腳本一些有用且很酷的東西

緩解ssh服務器雙重認證問題,他學到了許多有用且很酷的東西。


【轉載自:www.iHk-system.com|尋訪諸神的網站】

20130815203032260771.JPG

一、Colors your echo

大多數情況下,你希望輸出echo Color,比如綠色代表成功,紅色代表失敗,×××代表警告。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
NORMAL=$(tput sgr0)
GREEN=$(tput setaf 2; tput bold)
YELLOW=$(tput setaf 3)
RED=$(tput setaf 1)
functionred() {
echo -e "$RED$*$NORMAL"
}
functiongreen() {
echo -e "$GREEN$*$NORMAL"
}
functionyellow() {
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。

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

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

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

三、To check specific executable exists or not (檢查特定可執行的文件是否存在)

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

這裏使用which來命令查找可執行的curl 路徑。如果成功,那麼可執行的文件存在,反之則不存在。將&>/dev/null設置在輸出流中,錯誤流會顯示to /dev/null (這就意味着在控制板上沒有任何東西可打印)。

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

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

四、To print usage of scripts  (打印使用的腳本)

當我開始編寫shell 腳本,我會用echo來命令打印已使用的腳本。當有大量的文本在使用時, echo命令會變得凌亂,那麼可以利用cat來設置命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 默認值)

有時,如果用戶沒有設置值,那麼會使用默認值。

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

檢查URL環境變量。如果不存在,可指定爲localhost。

六、To check the length of the string 檢查字符串長度

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

利用 ${#VARIABLE_NAME} 定義變量值的長度。

七、To read inputs with timeout (讀取輸入超時)

1
2
3
4
5
6
7
8
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  (獲取目錄名和文件名)

1
2
3
4
5
6
7
8
# 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


【轉載自:www.iHk-system.com|尋訪諸神的網站】


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章