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来设置输出的颜色,更多使用见:http://linux.101hacks.com/ps1-examples/prompt-color-using-tput/
2.打印调试信息
function debug() {
if [[ $DEBUG ]]
then
echo ">>> $*"
fi
}
# For any debug message
debug "Trying to find config file"
3.打印脚本的使用信息
cat << EOF
Usage: myscript <command> <arguments>
VERSION: 1.0
Available Commands
install - Install package
uninstall - Uninstall package
update - Update package
list - List packages
EOF
可以扩展成多行注释
<< EOF
code.....
EOF
4.没有赋值时使用默认值
URL=${URL:-http://localhost:8080}
5.获取字符串长度
if [ ${#authy_api_key} != 32 ]
then
red "you have entered a wrong API key"
return $FAIL
fi
6.设置输入超时
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)
7.获取文件夹名和文件名
# 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`