(各语法逻辑通用)

1、if语句

结构:

if   condition
then 
      statements
else
      statements
fi

 

 

2、elif语句(类似c语言中,else if)

二者样例:

#!/bin/sh
echo -n "Is it morning? Please answer yes or no "
read timeofday

if [ "$timeofday" = "yes" ]; then
	echo "Good morning"
elif [ "$timeofday" = "no" ]; then
	echo "Good afternoon"
else
	echo "Sorry,$timeofday not recognized. Enter yes or no "
	exit 1
fi
exit 0

 

 

结果:

Is it morning? Please answer yes or no yes
Good morning

 

 

 

3、if中判断条件注意:

其使用变量时,应该用“”标记。以免出现不合法问题。导致出现 ?:unary operator expected错误

 

4、for循环

结构:

for variable in values
do
    statements
done

 

样例

#!/bin/sh

for foo in "bar fud 43"
do
	echo $foo
done
exit 0

 

结果:

bar fud 43

 

 

 

5、while语句

结构:

while condition do
       statements
done

 

6、until语句(do…while)

结构:

until condition
do
       statements
done

 

样例:

#!/bin/sh

until who ? grep "$1" > /dev/null
do
	sleep 60
done
# now ring

echo -e '\a'
echo *****$1 has just logged in*****
exit 0

 

结果;

case1 case1~ first for hanshu if tiaojian try_var until useofbianliang has just logged in*****

 

 

7、case语句:

结构:

case variable in
      pattern [ ? pattern ] ... )   statement;;
      pattern [ ? pattern ]... )    statement;;
      ....
esac

 

样例:

#!/bin/sh

echo "Is it morning? Please answer yes or no"
read timeofday

case "$timeofday" in
	yes) echo "Good morning";;
	no ) echo "Good afternoon";;
	y  ) echo "Good Mornig";;
	n  ) echo "Good Afternoong";;
	*  ) echo "Sorry, answer not recognized";;
esac

exit 0

 

结果:

Is it morning? Please answer yes or no
yes
Good morning

 

8、其他:与或(&& ||)