1.变量
shell变量无需声明.直接用即可.如:
a="GoodLuck!"
shell变量的引用前面加"$"符即可.如:
echo $a
实例:
#!/bin/sh
a="Hello,Shell!"
echo $a
更严格来说,引用shell中的变量.变量需要用"{}"括起来.如上述:
echo ${a}和echo $a效果是一样的.这样做的目的主要向shell中
表明一个字符串中哪一个才是变量.对比下面两份代码:
代码一:
#!/bin/sh
num=2
echo $numnd
执行无任何输出.因为shell找不到numnd的值.
代码二:
#!/bin/sh
num=2
echo ${num}nd
输出为2nd
2.if语句.
格式:
if空格[空格 condition 空格];空格then
do what you want to do
else
do what you want to do
fi
主要注意之间的空格.
实例:
#!/bin/sh
if [ "$SHELL" = "/bin/bash" ]; then
echo "Your Shell Is bash."
else
echo "Your Shell Is $SHELL."
fi
3.命令行参数
shell用read修饰的变量来实现命令行参数的传入.
实例:
#!/bin/sh
echo "Pls Input The Cmd-Line Argument:"
read cmdlineargument
echo "What You Input Cmd-Line-Argument is $cmdlineargument"
4.while循环
shell中while循环的语法如下:
while空格[空格condition空格];空格do
do what do you want to do
done
实例:
#!/bin/sh
cnt=0;
while true; do
while [ $cnt -lt 10 ]; do
echo $cnt;
# cnt=`expr $cnt + 1`;
cnt=$(($cnt + 1));
sleep 1
done
echo "To The End."
break;
done
注:上述中语句cnt=`expr $cnt + 1`;实现了变量自增.
5.for循环
shell中for循环的语法如下:
for var in ...
do
do what do you want to do
done
实例:
#!/bin/sh
for i in $(seq 1 10)
do
echo $i;
sleep 1;
done
6.case语句
类似C语言里面的switch...case语句.语法如下:
case ... in...) do something here ;;
esac
实例:
!/bin/sh
a="a";
b="b";
c="c";
q="q";
while true; do
read argument;
case $argument in
$a)
echo $a;;
$b)
echo $b;;
$c)
echo $c;;
$q)
break;;
esac
done