Shell技巧(一)

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`

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值