从Shell脚本中学到的知识
作者Fizer Khan是一位Shell脚本迷,他对有关Shell脚本新奇有趣的东西是如此的痴迷。最近他遇到了authy-ssh脚本,为了缓解ssh服务器双重认证问题,他学到了许多有用且很酷的东西。对此,他想分享给大家。
1. 为输出着色
大多数情况下,你希望输出带颜色的结果,比如绿色代表成功,红色代表失败,黄色代表警告。
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来设置颜色、文本设置并重置到正常颜色。想更多了解tput,请参阅prompt-color-using-tput。
2. 输出调试信息
输出调试信息只需调试设置flag。
Shell代码
function debug() {
if [[ $DEBUG ]]
then
echo ">>> $*"
fi
}
# For any debug message
debug "Trying to find config file" 某些极客还会提供在线调试功能:
Shell代码
# From cool geeks at hacker news
function debug() { ((DEBUG)) && echo ">>> $*"; }
function debug() { [ "$DEBUG" ] && echo ">>> $*"; } 3. 检查特定可执行的文件是否存在?
Shell代码
OK=0
FAIL=1
function require_curl() {
which curl &>/dev/null
if [ $? -eq 0 ]
then
return $OK
fi
return $FAIL
} 相关推荐
laisean 2020-11-11
大牛牛 2020-10-30
firefaith 2020-10-30
liguojia 2020-10-20
wangzhaotongalex 2020-10-20
JohnYork 2020-10-16
Julyth 2020-10-16
laisean 2020-09-27
flycappuccino 2020-09-27
liguojia 2020-09-27
wangzhaotongalex 2020-09-22
流年浅滩 2020-10-23
liujianhua 2020-10-22
woaimeinuo 2020-10-21
laisean 2020-09-01
vvu 2020-09-16
libao 2020-09-16
Yyqingmofeige 2020-08-18
zhushixia 2020-08-17