##### Shell script 的预定变量( $0,$1,$2...) #####
例如:[test@linux test]$ /home/ch07.sh hello world
$0 = /home/ch07.sh
$1 = hello
$2 = world
...
依此类推
##### 流程控制 #####
## if ... then
定义:
if [ 条件判断式1 ]; then
....
elif [ 条件判断式1 ]; then
....
else
....
fi
例如:用户输入one,two,three时,分别显示出他的选择,如果输入的不是one,two,three,则显示用法。
if ["$1" == "one" ]; then
echo "Your choice is ONE"
elif [ "$1" == "two" ]; then
echo "Your choice is TWO"
elif [ "$1" == "three" ]; then
echo "Your choice is THREE"
else
echo "Usage: $0 one|two|three"
fi
如果有多个条件要判断时,用 [ 条件1 ] &&(||) [ 条件2 ]
## case ... esac
定义:
case $变量名称 in
"变量内容1")
....
;;
"变量内容2")
....
;;
*)
....
;;
esac
还是用上面的例子来演示一下:
case $1 in
"one")
echo "Your choice is ONE"
;;
"two")
echo "Your choice is TWO"
;;
"three")
echo "Your choice is THREE"
;;
*)
echo "Usage: $0 one|two|three"
;;
esac
##### function #####
定义:
function fname(){
do something
}
利用function可以把重复的代码剥离出来,从而简化代码。function必须定义在脚本的最前面,这样脚本在执行时才能找到它。
function 也有预定变量$0,$1,$2...,使用和脚本的预定变量一样。不过所指的内容不一样,就是function里的$1 和脚本里的$1
指的不是同一个值。
例如上面的例子也可以这样写:
function printMsg(){
echo "Your choice is $1"
}
case $1 in
"one")
printMsg 1
;;
"two")
printMsg 2
;;
"three")
printMsg 3
;;
*)
echo "Usage: $0 one|two|three"
;;
esac
#
[test@linux test]$ /home/ch08.sh one
Your choice is 1