使脚本更具可移植


#!/usr/bin/env bash

布尔值

0:表示true 非0:表示false

function getB(){
	return 0
}

while getB; do
	echo "fuck"
	sleep 1
done

可以利用return 0表示true,return 1表示false.

if

if TEST-COMMANDS; then
    CONSEQUENT-COMMANDS
fi

if-else

if TEST_COMMANDS; then
    COMMANDS
else
    COMMANDS
fi

if-elif

if TEST_COMMANDS; then
    COMMANDS
elif TEST_COMMANDS; then
    COMMANDS
fi

if-elif-else

if TEST_COMMANDS; then
    COMMANDS
elif TEST_COMMANDS; then
    COMMANDS
else
    COMMANDS
fi

demo

if [ -z $1 ];then
	usage
	exit 0
fi

if [ $1 = "stop" ]; then
	stop
elif [ $1 = "start" ]; then
	start
elif [ $1 = "restart" ]; then
	stop
	start
else
	usage
fi

while

while TEST_COMMANDS ; do
    COMMANDS
done

demo

while [ $1 -gt 0 ] ; do
	sleep 2
	kill -0 $(getPID)
done

for

for i in `seq 1 10`; do
        echo $i
done
for i in $( ls ); do
    echo item: $i
done

function

function fname(){
    COMMANDS
}

注意,在function里,并不能直接使用从命令行里传入的参数的,而要在调用函数时,显式再次传递 如:

fname $1

函数返回值

function getPID(){
	# replace the grep content with your tomcat path, start with []
	local PID=`ps aux | grep "[a]pache-tomcat-7.0 (copy).63" | awk '{print $2}'`
	echo $PID
}

注意,bash里,return xxx可能并不是你想要的,它这样子并不是函数的返回值。要想使用函数的返回值,应该:


function getPID(){
	# replace the grep content with your tomcat path, start with []
	local PID=`ps aux | grep "[a]pache-tomcat-7.0 (copy).63" | awk '{print $2}'`
	echo $PID
}

local P_ID=$(getPID)

直接return,它表示的是函数执行完毕的状态结果。

例子

获取命令行执行的结果

local PID=`ps aux | grep "[a]pache-tomcat-7.0 (copy).63" | awk '{print $2}'`
echo $PID

即使用反单引号括住开头和结尾的命令行即可.

获取算术运算结果

H=$(( 3*4 ))
echo $H

暂停N秒

sleep N

判断字符串是否为空

if [ -z $1 ];then
	usage
	exit 0
fi

数学表达式比较

大于

[ ARG1 -gt ARG2 ]

大于等于

[ ARG1 -ge ARG2 ]

等于

[ ARG1 -eq ARG2 ]

不等于

[ ARG1 -ne ARG2 ]

小于

[ ARG1 -lt ARG2 ]

小于等于

[ ARG1 -le ARG2 ]

字符串比较

等于

[ STR1 == STR2 ]

不等于

[ STR1 != STR2 ]

大于

[ STR1 > STR2 ]

小于

[ STR1 < STR2 ]

忽略大小写

shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
shopt -u nocasematch

数字前补0

for i in {01..05}; do echo "$i"; done

检测某程序是否存在

stackoverflow

$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }

执行远程命令时注意

ssh user@server "df -h | grep /dev/root | awk '{print \$5}'"

要注意将 $ 转义.

获取当前外网IP

dig +short myip.opendns.com @resolver1.opendns.com

crontab 等待上次完成后再执行

#!/usr/bin/env bash

ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
cd ${ROOT}
pwd

md5value=`echo ${ABSOLUTE_PATH} | md5sum | awk '{print $1}'`

echo "${md5value}"

exec 9>"/tmp/${md5value}.flock"
if ! flock -n 9  ; then
     echo "`date` another instance is running" >> /tmp/${md5value}.console
     exit 1
fi
...你的脚本代码....