bash 常用代码片段

自己常用的一些代码片段,作为速查手册.


路径类:


获取脚本所在目录 (不是运行脚本的目录,是保存脚本的目录)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

按 前缀+当前时间戳 为规则命名的临时文件
TMP_FILE=/tmp/namestring_$(date +%m%d%H%M%S)

获取 git 项目的根目录:
GIT_PROJ_ROOT=$(readlink -f $(dirname $(git rev-parse --git-dir)))

获取 git 项目在远端服务器上的项目名:
GIT_PROJ_NAME=$(git remote -v | head -n1 | awk '{print $2}' | sed 's/.*\///' | sed 's/\.git//')


函数类:


带 DEBUG 开关的语句调试函数
DEBUG() {
    # execute cmd when $DEBUG is true
    if $DEBUG; then
        $@
    fi
}

# example:
DEBUG echo "print debug info"


脚本退出回调函数:
CLEAR_WORK() {
    # some clear work here, like purge tmp file
    if [ -e $TMP_DIR ]; then
        rm $TMP_DIR
    fi
}
trap "CLEAR_WORK" EXIT

脚本报错回调函数:
ERRORTRAP() {
    local shell_name=`basename $0`
    echo "==================="
    echo "MY SCRIPT ERROR: "
    echo "NAME: $shell_name"
    echo "ERRNO: $?"
    echo "==================="
}
trap "ERRORTRAP" ERR

判断是否数字,及数字是否在规定取值范围内:
# see if $1 is interger or not
# if $2, $3 is presented, see if $1 is inside [$2, $3] (both $2 and $2 are included)
# $2 and $3 should be interger
# yield true or false
function IsInteger() {
    local ret       #return value

    if [[ $1 =~ [0-9]+ ]]; then     #make sure input is interger
        ret="true"
    else
        ret="false"
    fi

    if [ "$ret" == "false" -o $# -eq 1 ]; then
        echo $ret
        return
    fi

    if [[ ( $1 -ge $2 ) && ( $1 -le $3 ) ]]; then      #make sure $n is inside the range
        ret="true"
    else
        ret="false"
    fi

    echo $ret
}

# example:
echo $(IsInteger 8)    # print true
echo $(IsInteger 8P)    # print false
echo $(IsInteger 8 2 10)    # print true

参数处理函数:
#process options
function ProcessOptions() {
    while getopts ":txdul:" opt; do
        DEBUG echo "opt: $opt"
        case "$opt" in
            "t")
                B_TOUCH_ENABLED="true"
                ;;
            "x")
                B_PUSH_TO_PHONE="false"
                ;;
            "u")
                B_UPDATE_API="true"
                ;;
            "d")
                DEBUG="true"
                ;;
            "l")
                optarg=$OPTARG
                ;;
            "?")
                #Unknown option
                echo "* unknown option: $opt"
                ShellHelp
                exit
                ;;
            ":")
                #an option needs a value, which, however, is not presented
                echo "* option -$opt needs a value, but it is not presented"
                ShellHelp
                exit
                ;;
            *)
                #unknown error, should not occur
                echo "* unknown error while processing options and params"
                ShellHelp
                exit
                ;;
        esac
    done
    return $OPTIND
}

#process args
function ProcessArgs() {
    DEBUG echo "args: $@"
    if [ $# -eq 0 ]; then
        echo "no args, just print help"
    fi

    for arg in $@; do
        echo $arg
    done
}

ProcessOptions "$@"
arg_start=$?
ProcessArgs "${@:$arg_start}"


语法类:


for 循环示例:
# 'for' loop example 1
for s in Shire RiverRun Moria Rohan Gondor MinasMorgul Mordor; do
    echo "a tour to Middle Earth: $s"
done

# 'for' loop example 2
for ((i=0; i<9; ++i)); do
    echo "how many free cities are there across the narrow sea? $i"
done

# 'for' loop example 3
ARRAY=(WinterFall Eyrie RiverRun CasterlyRock StormsEnd HighGarden SunSpear)
for castle in ${ARRAY[*]}; do
    echo "high sits of Seven Kingdom: $castle"
done

# 'for' loop example 4
for i in {1..7}; do
   echo "Voldemort will return in book $i ."
done

# 'for' loop example 4
# last param is step. bellow segment will print 5 lines
for i in {1..10..2}; do
   echo "the bear and the maiden fair. $i"
done

数组操作:

# evaluation example1
declare -a Starks
Starks[0]=Rob
Starks[1]=Jon
Starks[2]=Sansa
Starks[3]=Arya
Starks[4]=Brandon
Starks[5]=Rickon

Lannisters=([0]=Jaime [1]=Ceise [2]=Tyrion)
Baratheons=(Robert Stannis Renly)

# get
echo "oldest of the Starks: ${Starks[0]}"

# print all values in an array
echo "Eddard Stark's: ${Starks[*]}"
echo "Eddard Stark's: ${Starks[@]}"

# length of an array
echo "Tywin Lannister has ${#Lannisters[@]} children"



待续...


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值