shell----- 条件选择 if && case

来源:互联网 发布:读梦里花落知多少有感 编辑:程序博客网 时间:2024/04/30 14:35

1 if

#!/bin/bashecho "Please chose your favourite fruit:";select fruit in "apple" "orange" "banana" "none";dobreak;done;if [ $fruit == "apple" ]    then echo "you like apple!"elif [ $fruit == "orange" ]   then echo "you like orange!"elif [ $fruit == "banana" ]   then echo "you like banana!"else    echo "you dont like all this!"fi



注意:

1  

if [ $fruit == "apple" ]    then echo "you like apple!"
这个每一句话后面都可以加  ;  ,加上 ;  后的好处是,这两句话都写到一行里也不会有错误。

但是还是习惯空行比较好,空行后,就不用加  ;  也OK 拉~~

2

if  与 [ 之间要空格。。。。

[ 与后面那个字符之间也要空格, ] 与前面那个字符之间也要空格。。。

3

select fruit in "apple" "orange" "banana" "none"
do
break
done


这个是选择的,输入数字选择,然后变量 fruit = apple 了。。。

root@vivi-Ideapad-Z460:~# ./myshell.sh
Please chose your favourite fruit:
1) apple
2) orange
3) banana
4) none
#? 2
you like orange!


===================

嵌套:

if [ commond ]

  then  if [ commond2 ]

                then   doSomething

             fi

 fi


====================================================================================\

2 case


shell中的caseC/C++中的switch结构是相同的.它允许通过判断来选择代码块中多条路径中的一条。

case"$variable" in

"$condition1")

command...

;;

"$condition1")

command...

;;

esac

注意:对变量使用""并不是强制的,因为不会发生单词分离.

每句测试行,都以右小括号)结尾.

每个条件块都以两个分号结尾;;.

case块的结束以esac(case的反向拼写)结尾。



#!/bin/bashecho "Please chose your favourite fruit:"select fruit in "apple" "orange" "banana" "none"dobreakdonecase "$fruit" in"apple")  echo "you like apple!";;"orange")  echo "you like orange!";;"banana") echo "you like banana!";;"other")echo "you dont like all this!";;esac


对变量不使用""  变量颜色看着不舒服。。。

每个条件块都以两个分号结尾;;  ========这个我没有,貌似没有报错。。。

root@vivi-Ideapad-Z460:~# ./myshell.sh
Please chose your favourite fruit:
1) apple
2) orange
3) banana
4) none
#? 3
you like banana!



原创粉丝点击