Simple shell Script Programming example (looping)

Source: Internet
Author: User

For loop

For variable name in list;

Loop body

Done


Implementation mechanism:

Assigns the element in the list to the "variable name" in turn; The loop body is executed once each assignment; Until the elements in the list are exhausted, the loop ends

List Generation Method:

(1) Give the list directly

(2) List of integers:

(a) {start: End

(b) $ (seq[start [step]] end)

(3) command to return a list

$ (COMMAND)

(4) using glob, such as: *.sh

(5) variable reference;

[email protected], $*




1. Determine the type of all files in the/var/directory

#!/bin/bashfor filename in /var/* ;d o    if [ -l  "$ FileName " ] ;then        echo " $filename  is  Link file "    elif [ -f " $filename " ];then         echo  "$filename  is common file"     elif  [ -b  "$filename"  ];then        echo  "$ Filename is block file "    elif [ -c " $filename " ];then         echo  "$filename  is char file"      elif [ -S  "$filename"  ] ;then         echo  "$filename  is socket file "     elif [ -d   "$filename"  ] ;then        echo  "$filename  is directory"      else        echo  "Unknow"      Fidone

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/86/1E/wKiom1e1U97hkL0GAABAGaiHgLw020.png "title=" 1.png " alt= "Wkiom1e1u97hkl0gaabagaihglw020.png"/>

Ii

#!/bin/bashfor f1 in /var/* ; do    ff= ' ls -ld  $f 1  | cut -c1 '     case  $ff  in    l)          echo  "$f 1 is link file"     ;;     B)         echo  "$f 1 is blcok  file  "    ;;     c)         echo  "$f 1 is char  file "    ;;     s)         echo  "$f 1 is socket  file "    ;;     -)         echo  "$f 1 is file"     ;;     d)         echo  "$f 1  is diR "    ;;     *)         echo  "$f 1  is  other  "    esacdone

2, add 10 user user1-user10, password with user name

#!/bin/bash# Add 10 user user1-user10, password with user name for I in {1..10};d o ID user$i &>/dev/null if [$?-eq 0];then Echo "User$i is exist" else Useradd user$i echo "User$i" | passwd--stdin user$i &>/dev/null echo "Add user$i finished" fi done

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/86/1F/wKioL1e1WxeDzR0NAAAyMsVsKbg899.png "title=" 2.png " alt= "Wkiol1e1wxedzr0naaaymsvskbg899.png"/>

Ii

Delete the above user

#!/bin/bashfor i in {1..10};        Doid user$i &>/dev/null if [$?-eq 0];then userdel-r user$i echo "user$i is delete" Else echo "user$i isn't exist" fi done

3. The/ETC/RC.D/RC3.D directory has several files starting with K and beginning with S, respectively reading each file, the output of the file starting with K is the file plus stop, and the file output with s begins with the filename plus start;

The #!/bin/bash#/etc/rc.d/rc3.d directory has a number of files starting with K and beginning with S, respectively reading each file, the output of a file starting with K is a file plus stop, the file output with s begins with the filename plus start;for filename in/ etc/rc.d/rc3.d/*;d o ff= ' basename "$filename" |      Cut-c1 ' Case $ff in [Kk]) echo "$filename stop";;        [Ss])      echo "$filename start";; *) echo "other" Esacdone

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/86/1F/wKiom1e1Xg7xDxARAAAQmQEXreU427.png "title=" 3.png " alt= "Wkiom1e1xg7xdxaraaaqmqexreu427.png"/>

4, write a script, prompt to enter the value of positive integer n, calculate the sum of 1+2+3+...N

#!/bin/bashread-p "Please a number:" N1if [[$n 1 =~ ^-?[ [:d Igit:]]            +$]];then If [$n 1-gt 0];then sum=0 for i on ' seq $n 1 ';d o sum=$[$sum + $i] Done echo "Sum is $sum" Else echo "$n 1 was not positive integer" fi else echo "need a number" fi

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/86/1F/wKiom1e1YvnTc0wZAAAu7ONKDjk568.png "title=" 4.png " alt= "Wkiom1e1yvntc0wzaaau7onkdjk568.png"/>

5, write a script, prompt please enter the network address, such as 192.168.0.0, determine the input network segment host online status

#!/bin/bashread-p "Please input a IP:" Ipi= ' echo $ip |cut-d.-f1-3 '. if [[$ip =~ ^ ([1-9]|[ 1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) \. ([0-9]| [1-9] [0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) \.) {2} ([0-9]| [1-9] [0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) $]]; then for j in {1..255};d o ping-c1-w1 $i $j &>/dev/null && Amp echo "$i $j is on" | | echo "$i $j is Off" doneelse echo "This is not IP" fi~

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/86/1F/wKiom1e1Zc2hIkObAAA503Tnulo373.png "title=" 5.png " alt= "Wkiom1e1zc2hikobaaa503tnulo373.png"/>

6. Print 99 multiplication table

#!/bin/bashi=1for i in {1..9};d o to J in ' seq $i ';d o echo-ne "$j * $i =$[$i * $j]\t" Done Echodone

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/86/1F/wKioL1e1aELznNOnAAAqYwmQoKA497.png "title=" 6.png " alt= "Wkiol1e1aelznnonaaaqywmqoka497.png"/>

While loop


While CONDITION; Do

Loop body

Done


CONDITION: cyclic control conditions; Before entering the cycle, make a judgment; once each loop is judged again; the condition is "true", then a loop is executed until the condition test state is "false" to terminate the loop

Therefore: Condtion generally should have a cyclic control variable, and the value of this variable will be continuously corrected in the loop body

Entry condition: condition is true;

Exit Condition: Condition is false




1. The sum of all positive integers within 100

#!/bin/bashi=1sum=0while [$i-le];d o sum=$[$sum + $i] Let i++ do echo "Sum is $sum"

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/86/20/wKioL1e1ayCRMf4DAAAJMCKgsHQ978.png "title=" 7.png " alt= "Wkiol1e1aycrmf4daaajmckgshq978.png"/>


2, through the ping command to detect the 172.16.250.1-254 range of all the host's online status, statistics online host and the number of offline host.

#!/bin/bashread-p "Please input IP" ipi= ' echo $ip | cut-d.-f1-3 '. j=0if echo $ip | Egrep "^ ([1-9]|[ 1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) \. ([0-9]| [1-9] [0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) \.) {2} ([0-9]| [1-9] [0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]) $ "; then while [$j-le 255];d o ping-c1-w1 $i $j &>/dev/null &     amp;& echo "$i $j is on" | | echo "$i $j is Off" let J + + do else echo "This isn ' t IP" fi


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/86/20/wKiom1e1bJ-wMpcoAAA0PcbsdVM973.png "title=" w2.png "alt=" Wkiom1e1bj-wmpcoaaa0pcbsdvm973.png "/>

3. Print 99 multiplication table

#!/bin/bashi=1while [$i-lt];d o j=1 while [$j-le $i];d o echo-ne "$i * $j =$[$i * $j]\t" let J + + Do echo let i++ do

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/86/20/wKiom1e1be-AH7O2AAAruAdrxvE147.png "title=" w3.png "alt=" Wkiom1e1be-ah7o2aaaruadrxve147.png "/>

4. Generate 10 random numbers using variable random, output this 10 number, and show the largest and smallest of them

#!/bin/bashi=1a= $RANDOMmax = $amin = $awhile [$i-le];d o [$max-le $a] && max= $a [$min-ge $a] &&am P Min= $a echo "$a" a= $RANDOM let i++ doneecho "max number was $max" echo "min number is $min" ~

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/86/21/wKiom1e1dGaCT6wFAAAfaDZQCZs702.png "title=" w4.png "alt=" Wkiom1e1dgact6wfaaafadzqczs702.png "/>

5. Print Chess board

#!/bin/bashi=1while [  $i  -le 8 ];d o      j=1     while [  $j  -le 8 ];d o         sum=$[$i + $j]      n=$[$sum%2]         if [  $n  -eq 0 ];then             echo -ne  "\033[41;1m  \033[0m"          else             echo -ne  "\033[43;1m  \033[0m"         fi        let j++     done     let i++     echodone 

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/86/21/wKiom1e1eH_ThwuhAAALvKZfmkg986.png "title=" w5.png "alt=" Wkiom1e1eh_thwuhaaalvkzfmkg986.png "/>

Until cycle

Until CONDITION; Do

Loop body

Done


Entry condition: CONDITION is False

Exit Condition: CONDITION is True


1, every 3 seconds to the system to obtain the information of the user who has logged on, if the user hacker logon, the logon time and the host record in the log/var/log/login.log, and prompts the user to exit the system.

#!/bin/bashuntil who | Grep-q "^hacker\>"; Dosleep 3donewho| grep "^hacker\>" | Tr-s "" | Cut-d ""-f3-5 >>/var/log/login.logecho "You should logout" | Mail Hackerecho "Hacker is login"

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/86/21/wKiom1e1fiSBsk24AAASS1lYz9E786.png "title=" u1.png "alt=" Wkiom1e1fisbsk24aaass1lyz9e786.png "/>

2, randomly generated within 10 of the number, to achieve the word guessing game, the hint is relatively large or small, equal to exit.

#!/bin/bashread -p  "guess number! please enter a numer{0-10}: "   nif [[  $n  =~ ^[[:d igit:]]+$ ]] ;then    i=$[$RANDOM%11]     until [  $n  -eq  $i  ] ; do         if [  $n  -gt  $i  ] ; then             echo  "It ' s too large "          else              echo  "It ' s too small "         fi           read -p  "Try again:"  n     done    echo  "You are right!!!" else    echo  "please input a number !!! " Fi

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/86/21/wKioL1e1gXygM0LZAAAdLdpd9rg068.png "title=" u2.png "alt=" Wkiol1e1gxygm0lzaaadldpd9rg068.png "/>

1, write a script: print isosceles triangle

#!/bin/bashread -p  "please input a line number "  nif [[  "$n"  =~ ^[[:d igit:]]+$ ]] ;then     for i in  ' seq   $n '  ;d o           for j in  ' seq $[$n-$i] ';d o            echo -n   " "         done         for k in  ' seq $[$i *2-1] ';d o             echo -n  "*"         done         echo        let i++      doneelse    echo  "need a number!"     exit 2fi

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/86/21/wKioL1e1ghvDv1ggAAALsc9GI7Y890.png "title=" z1.png "alt=" Wkiol1e1ghvdv1ggaaalsc9gi7y890.png "/>

2, using until cycle to achieve the chess board

#!/bin/bashi=1red= "\033[41;1m  \033[0m" yellow= "\033[43;1m   \033[0m "until [  $i  -gt 8 ] ;d o    j=1      until [  $j  -gt 8 ] ;d o         sum=$[$i + $j]        z=$[$sum%2]         if [  $z  -eq 0 ] ;then             echo -ne  "$red"          else             echo -ne   "$yellow"         fi           let j++     done    let i++      echodone 

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/86/21/wKiom1e1goiwEvLDAAALKj-xgZU088.png "title=" z2.png "alt=" Wkiom1e1goiwevldaaalkj-xgzu088.png "/>

This article is from the "I ' m Groot" blog, so be sure to keep this source http://groot.blog.51cto.com/11448219/1840068

Simple shell Script Programming example (looping)

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.