1、Give ECHO colors see see!
NORMAL=$(tput sgr0)
GREEN=$(tput setaf ; tput bold)
YELLOW=$(tput setaf )
RED=$(tput setaf ) 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."
关于上面这个,我个人感觉不是很好,还有别的方法,以后再说吧!
2、打印 Debug 信息
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 ">>> $*"; }
3、检查可执行文件是否存在:
OK=
FAIL= function require_curl() {
which curl &>/dev/null
if [ $? -eq ]
then
return $OK
fi return $FAIL
}
其实也就一行就可以解决:function require_curl() {which culr &>/dev/null;}
4、打印命令的使用方式:
cat << EOF Usage: myscript <command> <arguments> VERSION: 1.0 Available Commands install - Install package uninstall - Uninstall package update - Update package list - List packages EOF
5、给变量加默认值:
URL=${URL:-http://localhost:8080}
6、检查字符串变量的长度:
if [ ${#authy_api_key} != ]
then
red "you have entered a wrong API key"
return $FAIL
fi
7、半延迟读取数据:
READ_TIMEOUT=
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)
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`
此文出自老外,觉得挺好,就译了过来!不算盗版吧,哈哈!
学一点,收获一点。学到的都是自己的!