Shell control Flow Structure notes

Source: Internet
Author: User
Tags case statement ssh server

Man test can see these  Comparison symbol:-lt less than-le less than or equal to-gt greater than-ge greater than or equal to-ne does not equal-eq equals < less than (requires double brackets), such as: (("$a" < "$b") <= less than or equal to (requires double brackets), such as: (("$a" <= "$b")) > Greater than (requires double brackets), such as: (("$a" > "$b") >= greater than or equal (requires double brackets), such as: (("$a" >= " $b "))= or = = (requires double brackets), such as: if ["$a" = = "$b"]           -b file             If the file exists and is a block special file, then true            -c file             If the file exists and is a character special file, then true            -d file             If the document exists and is a directory, then true           &NBSP;-E File             If document exists, then true            -f file     &nbs P       If the file exists and is a rule file, true            -g file           & nbsp: If the file exists and the Sgid bit value is set, true            -h file             If the file exists and is A compliance link is true            -k file             If the file exists and the value of "sticky" bit is set &N Bsp          -p file             If the file exists and is a named pipe, then true       & nbsp   &NBSp;-r file             If document is present and readable, then true            -s file   &N Bsp         If the file exists and its size is greater than 0, then true            -u file         &N Bsp   If the file exists and the SUID bit is set, true            -x file             If the file exists and can be True            -o file             If the file exists and is owned by a valid user ID.   -Z string           If string length is 0 true            -n string           If string length is not 0, then true           &NBSP;STRING1 = string2   If two strings are equal, true           &NBSP;STRING1! = string2 If two strings Not equal, true     if  then Else statement:  if condition 1    then command 1 elif   condition 2    &NBSP ; then   command 2 else         command 3&NBSP;FI complete     if and then on the same line that command format is the IF condition 1;then& nbsp;eg:#### #vim name.sh#!/bin/bash#name.shecho-n "Enter you name:" Read Nameif ["$NAME" = = ""]; then   echo "Do not enter your name" else   echo "you name is: $NAME" fi### #保存退出, chmod +x name.sh### # run./name.sh[[email protected] ~]#./name.sh enter you Name:tony (the name you are typing) you name is:tony  Eg:copy a file, if the file does not exist will prompt the system error information, and prompts yourself to give the information # # #vim Ifcp.sh#!/bin/bash#ifcp.shif cp test1.txt MyFile.txt; then   echo "Copy is successful" else   echo "' basename $ ': NoSuch test1.txt file ">&2fi### #保存退出, chmod +x ifcp.sh### #运行./ifcp.sh  -n (-n parameter to check script for syntax errors) [[email  Protected] ~]#/ifcp.sh cp:cannot stat ' test1.txt ': No such file or directoryifcp.sh:no such test1.txt File eg : Copy a file, the file does not exist system prompt information does not appear on the screen, display prompts yourself to give the information # # #vim ifcp.sh#!/bin/bash#ifcp.shif CP test1.txt myfile.txt 2>/dev/null ; then   echo "Copy is successful" else   echo "' basename $ ': No such test1.txt file" >&2fi### #保存 Exit, chmod +x ifcp.sh### #运行./ifcp.sh[[email protected] ~]#./ifcp.sh ifcp.sh:no such test1.txt file  Eg:copy a file, the file exists prompts the copy is successful### #vim ifcp.sh#!/bin/bash#ifcp.shif cp 1.txt myfile.txt 2>/dev/null; then   echo "Copy is successful" else   echo "' basename $ ': No such test1.txt file"  fi### #保存退出, chmod +x ifcp.sh### #运行./ifcp.sh[[email protected] ~]#./ifcp.sh copy is successful[[email protected] ~ ]# Cat myfile.txt the End Explanation: ' Bsename $ ' value displays the name of the current script or command, $ displayWill include the path of the current script or command       &NBSP;&GT;&AMP;2 Redirect to standard error, output to on-screen  eg: an If---elif statement---elif--else,- Z Parameters do not know what it means, you can see the man test, note the space and semicolon, quotes # # # #vim  ifelse.sh#!/bin/bash#ifelse.shecho-n "Enter Your name:" Read Nameif [-Z $NAME] | | ["$NAME" = ""];then   echo "do not enter a NAME" elif ["$NAME" = "root"];then   echo "Hello R" Oot "Elif [" $NAME "=" Tony "];then   echo" Hello Tony "else   echo" Hi, $NAME "fi### #保存退出, chmod +x ifelse . sh### #运行./ifelse.sh[[email protected] ~]#./ifelse.sh enter your Name:roothello root[[email  Protected] ~]#./ifelse.sh enter your Name:tonyhello tony[[email protected] ~]#./ifelse.sh enter your Name:jiehi,jie case statement:   case value in    mode 1)       Command 1   ;;Mode 2) Command 2   ;;Esac   case The value must be followed by the word in, and each pattern must end with a closing parenthesis. The value can be either a variable or a constant, the matching discovery value conforms to a pattern, and the period   all commands begin to execute until;;. Pattern Matching * Denotes any character,? Represents any single character, [...] Represents any character in a class or range  eg:##### #vim case.sh#!/bin/bash#case.shecho-n "Enter a number from 1 to 3:" Read anscase $ANS in  &N bsp;1)       echo "you select 1"      ;;    2)      echo "you select 2"      ;;    3)     echo "you select 3"    ;;    *)     echo "' BaseName $ ': This was not between 1 and 3" >&2    exit   ;; esac#### #保存退出, chmod + case.sh### #运行./case.sh[[email protected] ~]#./case.sh enter a number from 1 to 3:1you SE Lect 1[[email protected] ~]#./case.sh enter a number from 1 to 3:2you select 2[[email protected] ~]#./cas E.sh enter a number from 1 to 3:3you select 3[[email protected] ~]#./case.sh enter a number from 1 to 3:5c Ase.sh:this is not between 1 and 3  for cycle:   for variable name in list    do            Command 1 Command 2Done      When the value of a variable is in the list, the For loop executes all commands once, using the variable name to access the list, the command can be any valid shell command and statement, the variable name is any word, the in list usage is optional, and if not, the For loop uses the command-line positional arguments. The in list can contain replacements, strings, and file names. The argument behind  eg:in is a list # # # # # # # # # #vim For1.sh#!/bin/bash#for1.shfor loop in 1 2 3 4 5do   echo $loopdone # # # #保存退出, chmod +x for1.sh### #运行./for1.sh[[email protected] ~]#./for1.sh 12345eg:in after the argument is a string # # # # # # # # # #vim for2.sh# For2.shfor loop in "Orange red Bue Grey" do  echo $loop "done### #保存退出, chmod +x for2.sh### #运行 ./for2.sh[[email  Protected] ~]#./for2.sh orange Red Bue Grey put the contents of the for2.sh for loop in "Orange red Bue Grey"   change it to a for loop in orange Red Bue Greyz in the back of the branch shows the argument behind  eg:in as a command, "the system command is inside the back quote #vim for3.sh#!/bin/bash#for3.shfor Jie in ' cat MyFile.txt ' do    echo $jiedone # # # #保存退出, chmod +x for3.sh   [[email protected] ~]# cat Myfile.txt the end[[email protected] ~]#./for3.sh    theend eg: A for and if combination of the # # # # #vim For4.sh #!/bin/bash#for4.shecho "Zhe li Mian end you yi ge End"; myfile.txtfor JIE in ' cat myfile.txt ' do    If ["$JIE" = "End"];then       echo "It is: $JI E "    else       echo" It is isn't end,it is: $JIE "    fidone#### #保存退出, chmod +x For4. sh### #运行./for4.sh[[email protected] ~]#./for4.sh it are not end,it Is:zheit are not end,it is:liit are not end,it Is:mianit Is:endit are not end,it is:youit are not end,it is:yiit are not end,it Is:geit Is:end until cycle:   unt Il conditions    do         Commands 1Command 2    ...The done condition can be any test condition, and the test occurs at the end of the loop, so the loop executes at least once eg: check the size of the disk space, check the disk space every 300s, send the message to the root user ##### the specified number #vim until.sh#!/bin/bash# until.shpart= "/home" look_out= ' df | grep "$Part" | awk ' {print $} ' | Sed ' s/%//g ' echo $LOOK _outuntil ["$LOOK _out"-GT "]do echo" This Filesystem is empty "|mail root look_out= ' df | grep "$Part" | awk ' {print $} ' | Sed ' s/%//g ' Sleep 300done # # # # #保存退出, chmod +x until.sh### #运行./until.sh while loop: while command doCommand 1Command 2    ... Done  between while and all usually refers to using a command, but can put a few commands, the command is usually used as a test condition   eg:##### #vim while.sh#!/bin/bash#while.shname= name.txtif [ -e "$NAME"  ];then      echo-e "Zhui jia \ Jin qu \ yi Juhua" >> $NAME &NB Sp   else       touch $NAME       echo-e "Zhe ge Wen jian \ shi xin \ Jian de" ; $NAMEfiwhile Read linedo     echo $LINE  done < $NAME ##### #保存退出, chmod +x while.sh### #运行. While.shif [ -e "$NAME" &NBSP;]    //judge this file has wood, if there will be added a word, no will create a new file, then add a sentence and then through the loop to show him the output, if there is no this file, The first run will only appear echo-e "Zhe ge wen jian \ n shi xin \ Jian de" > $NAME this inside, if run second time, then Echo-e "Zhe ge wen jian \ n Shi xin \ N Jian de "> $NAME will be displayed once, then Echo-e" Zhui Jia \ n jin qu \ yi Juhua ">> $NAME will be entered once, run the third time, echo-e" Zhui Jia \ n ji n qu \ juhua ">> $NAME              will show more  break control:  exit loop if it is in an embedded Ring, you can specify N to jump out of the number of loops, eg:##### #vim BREAK.SH#!/BIN/BASH#BREak.shwhile:d o     echo-n "Enter any number [ 1...5]:"      read  ANS  &NB Sp;case   $ANS in     1|2|3|4|5)         echo "Your Enter a number between 1 and 5."        ;;      *)         echo "wrong number,bye."         break       ;;     esacdone##### #保存退出, chmod +x break.sh### #运行./break.sh[[email protected] ~]#./break.sh enter Any number [ 1...5]:1your Enter a number between 1 and 5.Enter any number [ 1...5]:3your Enter a number BETW Een 1 and 5.Enter any number [ 1...5]:7wrong Number,bye. Explanation: While:, the while is followed by one: indicates that the while statement is always true and jumps out of the loop with a break.  continue control:    Skip loop step  eg:#### #vim breakcontinue.sh #!/bin/bash#break.shwhile:d o     echo-n "Enter any number [ 1...5]:"      read  ANS   case   $ANS in& nbsp    1|2|3|4|5)         echo "Your Enter a number between 1 and 5."        ;;      *)         echo-n "wrong number,continue (y/n?)."         Read is_continue        case $IS _continue in        &N Bsp    y|yes| y| Yes)                  continue;            &NBSP ;    ;;               *) break                 ;;         esac       ;;     esacdone##### #保存退出, chmod +x breakcontinue.sh #### #运行,./breakcontine.sh[[email protected] ~] #./breakcontinue.sh enter any number [ 1...5]:3your Enter A number between 1 and 5.Enter any number [ 1 ... 5]:7wrong number,continue (y/n?). Yenter any number [ 1...5]:6wrong nUmber,continue (y/n?). N    vim Check_server.sh#####!/bin/bashecho "This script would to find which service has started"   #to Find www servicetesting= ' Netstat-tlun | grep ":" If [-N "$testing"];then                # #if no null is true  &NB Sp echo "WWW server has started!" fi  #to Find vsftpd servicetesting= ' Netstat-tlun | grep ": +" ' If ["$testing"! = ""];then            ## #if no null is true    echo " VSFTPD Server has started! " fi  #to find ssh servicetesting= ' Netstat-tlun | grep ":" If [-N "$testing"];then    echo "SSH server has started!" fi  #to Find mail servicetesting= ' Netstat-tlun | grep ":" ' If ["$testing"! = ""  ];then    echo "MAIL server has started!" Fi #####   function features   format: function fname () {  program segment}function settings Be sure to have built-in variables at the front of the program, $ 0 indicates the function name, followed by a variable labeled $1,$2,$3.... vim func.sh####!/bin/bashfunction PRIntinfo () {    echo "You choice is"}case in    "one") Printinfo;echo $ | tr-s ' A-Z ' A-Z ;;    "both")         Printinfo;echo $ | Tr-s ' A-Z ' A-Z '        ; ESAC  ####   shell Script Implementation 1+2+...+100vim Sum.sh#####!/bin/bashi=0s=0while ["$i"-lt   i=$ (($i + 1))     s=$ (($s + $i)) Doneecho "1+2+3+...+ $i = $s" # # # # # # # # # # #     vim sum1.sh#####! /bin/bashs=0for ((i=0;i<=100;i++)) do    s=$ (($s + $i)) Doneecho "1+2+". +100= $s another format for "echo" i= $i "#### for  vim for.sh#####!/bin/bashfor animal in cat dog pigdo      & nbsp Case $animal in                "cat")             &NB Sp           echo "$animal Miao Miao Jiao"                 &N Bsp      ;;                 "dog")                 &NBS P       echo "$animal Wang Wang Jiao                        ;;                 "pig")                 &NBS P       echo "$animal Luo luo jiao"                     &NBS P  ;                 "*")                         echo "$animal Jiao Mei Jiao"                     &N Bsp  ;         esacdone####

Shell control Flow structure notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.