Bash笔记
函数
function hello {
echo "hello, $*"
}
分支判断
case "$1" in
1) echo "a";;
2) echo "b";;
*) echo "c";;
esac
echo -n "Do you agree with this? [yes or no]: "
read yno
case $yno in
[yY] | [yY][Ee][Ss] )
echo "agreed"
;;
[nN] | [n|N][O|o] )
ehco "not agreed"
;;
esac
循环
for i in $(ls); do
echo $i
done
for i in `seq 1 10`; do
echo $i
done
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo $COUNTER
let COUNTER=COUNTER+1
done
COUNTER=20
util [ $COUNTER -lt 10 ]; do
echo $COUNTER
let COUNTER-=1
done
条件判断
if [ "foo" == "$1" ]; then
echo "a"
else
echo "b"
fi
常用条件
[ -a FILE ] # 是否文件存在
[ -b FILE ] # 是否block文件
[ -c FILE ] # 是否字符文件
[ -d FILE ] # 是否目录存在
[ -e FILE ] # 是否文件存在
[ -f FILE ] # 是否普通文件
[ -h FILE ] # 是否符号链接
[ -p FILE ] # 是否管道
[ -r FILE ] # 是否可读
[ -s FILE ] # 是否非空文件
[ -w FILE ] # 是否可写
[ -x FILE ] # 是否可执行
[ FILE1 -nt FILE2 ] # 是否FILE1比FILE2新
[ FILE1 -nt FILE2 ] # 是否FILE1比FILE2旧
[ -z STRING ] # 是否空字符串
[ -n STIRNG ] # 是否非空字符串
[ STRING ] # 是否非空字符串
[ STRING1 == STRING2 ] # 是否STRING1等于STRING2
[ STRING1 != STRING2 ] # 是否STRING1不等于STRING2
[ STRING1 < STRING2 ] # 是否STRING1小于STRING2
[ STRING1 > STRING2 ] # 是否STRING1大于STRING2
[ ARG1 OP ARG2 ] # 关系判断。OP是-eq, -ne, -lt, -le, -gt, -ge之一。
# 复合条件
[ !EXPR ]
[ (EXPR) ]
[ EXPR1 -a EXPR2 ] # and
[ EXPR1 -o EXPR2 ] # or
本地变量
function foo {
local x=1
echo $x
}
用户接口
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done
read name email
echo $name $email
参考资料