下面的例子展示了如何向脚本传递参数、脚本如何获取参数、if else判断、变量的使用等基本内容。
#!/bin/bash
# 如果参数个数大于1
if [[ $# -lt 1 ]]; then
echo "args count must > 1"
echo "Uage: bash +x example01.sh [args...]"
exit
fi
# 获取传递的参数并赋值给arg
arg=$1
if [[ $arg -gt 10 ]]; then
echo "$arg > 10"
else
echo "$arg < 10"
fi
这个脚本的调用方式如下:
bash +x example01.sh 5
下面的例子展示了数组、函数、循环等基本使用。
#!/bin/bash
if [[ $# -lt 1 ]]; then
echo "args count must > 1"
echo "Uage: bash +x example01.sh [args...]"
exit
fi
# 当前命令行所有参数。置于双引号中,表示个别参数
args=$@
for arg in $args; do
echo $arg
done
function fun() {
echo $1
}
fun "hello shell"
fun2() {
echo "Linux"
}
fun2
注意,函数fun中的$1,获取的是函数参数,不是脚本调用时传入的参数。$@ 是获取脚本调用时传入的参数列表。
while 循环以及其他几种循环、case、表达式expr的使用
#!/bin/bash
if [[ $# -lt 1 ]]; then
echo "args count must > 1"
echo "Uage: bash +x example01.sh [args...]"
exit
fi
case $1 in
"install" )
echo "operation type is install"
;;
"uninstall" )
echo "operation type is uninstall"
;;
* )
echo "operation type is not support"
;;
esac
for ((i=0;i<3;i++))
do
if ((i==1))
then
continue
fi
echo $i
done
for i in `seq 5`
do
echo "loop $i"
done
注意这里的case * 并不是所有,而是输入值不在case中,相当于default. 在循环中可以使用continue/break等关键字,非常类似java等其他语言的循环。