你的位置:首页 > 操作系统

[操作系统]Shell流程控制(if,else,case,while,for,until)

1.条件选择


1.1.if 语句

  语法十分简单

#!/bin/bashMATH_SCORES="$1"NAME="$2"if [ -z "${MATH_SCORES}" ]then printf "The command requires that options have a scores.\n" printf "What's ths scores of your math? :" read MATH_SCORESfiif [ -z "${NAME}" ]then printf "The command requires that options have a student's name.\n" printf "What's your name? :" read NAMEfiif [ "${NAME}" = "sunny" ]then printf "No, sunny is a teacher.\nPleae input your name,ok? " read NAME printf "My god,i think, you are bann sunny, excuse me.\n\n"else printf "\n"fiif [ "${MATH_SCORES}" -ge 90 ]then echo "Your scores is very good.Congratulations to you, ${NAME}." echo "I hope that you are't sunny."else if [ "${MATH_SCORES}" -ge 60 ]then echo "Congratulations. ${NAME}"elif [ "${MATH_SCORES}" -ge 50 ]then echo "Come on ${NAME}."else echo "What are you interested in? Please tell me, maybe i can help you, "${NAME}" ?"fi;fiecho[web@h p]$ ./if_then_else.sh 37The command requires that options have a student's name.What's your name? :sunnyNo, sunny is a teacher.Pleae input your name,ok? sunnyMy god,i think, you are bann sunny, excuse me.What are you interested in? Please tell me, maybe i can help you, sunny ?

  语句体,以fi结束。

 

  利用选择语句判断变量获取成功与否

JAVA_PATH=`which java 2>/dev/null`if [ "x$JAVA_PATH" != "x" ]; then JAVA_PATH=`dirname $JAVA_PATH 2>/dev/null` JRE_HOME=`dirname $JAVA_PATH 2>/dev/null`fi

 

1.2.case 语句

  双分号不能少;跟if一样,语句体也需要结束符。

  找工作时,根据应聘岗位不同,给出不同应征者相应的联系人信息。

#!/bin/bashecho -e "\v\tRecruitment Announcement"echo "Are you ready to apply for any job?"echo "1 accounting"echo "2 cashier"echo "3 secretary"echo -e "\vPlease enter a number to select the corresponding positions."read NUMcase $NUM in 1) printf "call mr wang. number is 1124\n" ;; 2) printf "call miss li. number is 1233.\n" ;; 3) printf "call miss ji. number is 1367.\n" ;; *) printf "If you want to make a lot of money, to be a seller. call 1498.\n" ;;esac

 

  在输出交互信息时,使用了echo命令。当要格式化输出时,需要来回调试。这里仅仅为了熟悉下case语句的语法,更好的方法在“cat”博文里重新实现。

   使用case语句,处理坐标移动的结果。

#!/bin/bashecho $(date)X1=0Y1=0echo "L - turn left"echo "R - turn right"echo "U - turn up"echo "D - turn down"read INScase $INS in L) X1=$[${X1}-1] ;; R) X1=$[${X1}+1] ;; U) Y1=$[${Y1}+1] ;; D) Y1=$[${Y1}-1] ;; [[:lower:]]) printf "Uppers, please.\n" ;; *) ;;esacecho "x = ${X1} y = ${Y1}"

 

  输出脚本的帮助信息:

case "$1" in "")  run_it  ;; -r|--read)  read_it  ;; -v|--version)  display_version  ;; --clear)  clear_TMPFILE  ;; -h|--help)  display_help  ;; *)  echo "findTom -h"  display_help  ;;esac

如果“"-v|--version"”,以双引号表示,会出现意外。要是想用,就该这么写:“"-v"|"--version"”。

 

1.3.通过辑判断实现条件测试

[view@file donatello]$ [ 3 -gt 5 ] && echo "true " || echo "false "false[view@file donatello]$ [ ! 3 -gt 5 ] && echo "true " || echo "false "true[work@file donatello]$ [ ! 3 -gt 5 ] && ( echo -n "true, "; echo "exit 0" ) || ( echo -n "false, "; echo "exit 1" )true, exit 0[work@file donatello]$ [ 3 -gt 5 ] && ( echo -n "true, "; echo "exit 0" ) || ( echo -n "false, "; echo "exit 1" )false, exit 1

 

2.循环


 

2.1.for循环

  语法格式:

for name[ [in [words…] ] ; ] do commands; donefor ((expr1;expr2;expr3)) ; do commands; done

 

[web@h p]$ ls >> java.dir[web@h p]$ cat java.sh#!/bin/bash for i in $(cat java.dir)do echo $idone

 

计算1加到10

#!/bin/bashdeclare -i sum=0for i in {1..10}do  sum=$((sum+i))doneecho sum = $sum#!/bin/bashsum=0for i in $(seq 1 10)do  sum=$((sum+i))doneecho sum = $sum

 

for 语句不带列表,就从命令行获取列表信息

[web@h p]$ cat t1.sh#!/bin/bash for ido echo $idone[web@h p]$ sh t1.sh lsls[web@h p]$ sh t1.sh `ls`

 

类C风格(体现在“for”语句中、以及循环体中;变量不需要“$”符号)

#!/bin/bashSUM=0MAX=100MIN=0for ((i=MIN; i<= MAX; i++))do SUM=$[SUM+i]doneecho "From ${MIN} add to ${MAX} is $SUM."

 

2.2.循环until、while

  条件判断时如果涉及了命令的返回值,该值不管返回了0还是1之类,都需要跟数字比较来控制程序的运行。

#语法
until test-commands; do consequent-commands; donewhile test-commands; do consequent-commands; done

 

  while循环是条件满足时开始执行;until循环是条件不满足时开始循环。

  举个例子,条件为假时,才能执行循环体语句:

#!/bin/bashuntil falsedo  echo -n '-'  sleep 1  echo -e -n '\b\'  sleep 1  echo -e -n '\b-'  sleep 1  echo -e -n '\b/'  sleep 1  echo -e -n '\b*'done

 

  若是换作了条件满足时执行循环体语句的情况,就可以选择while语句。

  while还可以直接读取文件,在done语句处“done < /path/to/file”。查看系统默认挂载的特殊文件系统:

#!/bin/bash#while read LINE; do  echo $LINE | grep -v dev &> /dev/null  if [ $? -eq 0 ]; then    echo $LINE | awk '{print $1}' | grep -v boot  fidone < /etc/fstab

 


bash脚本调试

  检查脚本语法、调试执行脚本

$ bash -n adduser.sh$ bash -x adduser.sh

 

  shell脚本追踪

  在测试脚本时,可以使用set命令进行运行时的追踪。在脚本中加入一行“set -x”;以“+”开头的行,就是获得的追踪内容(程序的执行过程)。

[root@right mag]# cat tes.sh #!/bin/bashset -xread -p "How old are you? " answerif [ $answer == "34" ]; then echo "Yes, very good."else echo "No, i don't want say anyting."fiexit 0[root@right mag]# ./tes.sh + read -p 'How old are you? ' answerHow old are you? 34+ '[' 34 == 34 ']'+ echo 'Yes, very good.'Yes, very good.+ exit 0[root@right mag]# ./tes.sh + read -p 'How old are you? ' answerHow old are you? 33+ '[' 33 == 34 ']'+ echo 'No, i don'\''t want say anyting.'No, i don't want say anyting.+ exit 0

 

  看看没有追踪的执行过程:

[root@right mag]# ./tes.sh How old are you? 32No, i don't want say anyting.