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 successgreen "Task has been completed"# To print errorred "The configuration file does not exist"# To print warningyellow "You have to use higher version."
?使用tput来设置输出的颜色,更多使用见:http://linux.101hacks.com/ps1-examples/prompt-color-using-tput/
2.打印调试信息
function debug() { if [[ $DEBUG ]] then echo ">>> $*" fi}# For any debug messagedebug "Trying to find config file"?3.打印脚本的使用信息
cat << EOFUsage: myscript <command> <arguments>VERSION: 1.0Available Commands install - Install package uninstall - Uninstall package update - Update package list - List packagesEOF
?
4.没有赋值时使用默认值
URL=${URL:-http://localhost:8080}5.获取字符串长度
if [ ${#authy_api_key} != 32 ]then red "you have entered a wrong API key" return $FAILfi?6.设置输入超时
READ_TIMEOUT=60read -t "$READ_TIMEOUT" input# if you do not want quotes, then escape itinput=$(sed "s/[;\`\"\$\' ]//g" <<< $input)# For reading number, then you can escape other charactersinput=$(sed 's/[^0-9]*//g' <<< $input)
?7.获取文件夹名和文件名
# To find base directoryAPP_ROOT=`dirname "$0"`# To find the file namefilename=`basename "$filepath"`# To find the file name without extensionfilename=`basename "$filepath" .html`
?