Shell Script Programming Learning notes-while loops

Source: Internet
Author: User
Tags case statement log log apache log

1. When type cycle and until type cycle

While using a few, the general daemon program or always loop execution will be used, the other loop operations are used for instead.

1.1 Type and until type loop syntax

(1) While conditional statement

Grammar:

While condition

Do

Instructions....

Done

Cell phone Recharge: Send SMS deduction fee, recharge 100, each buckle 1 corner 5, when the cost is less than 1.5 cents can not be sent.

(2) until conditional statement

Grammar:

Until conditions

Do

Instructions...

Done

Hint: only cycle once, the application scene is not many, understanding is good.

Basic examples of 1.2-type and until-type loops

Rest command: Sleep rest for 1 seconds, usleep1000000 rest for 1 seconds. Use timed tasks for up to one minute.

1.2.1 Example 1: Recording system load every 2 seconds

Method One: Every 2 seconds the screen output load value

[[email protected] jiaobenlianxi]# cat while1.sh #!/bin/shwhile true   do    uptime    sleep 2   done

Tip: While true indicates that the condition is always true and therefore executes, like a dead loop, which we call a daemon.

[[email protected] jiaobenlianxi]# sh while1.sh  02:50:13 up 1 day, 11:47,  3 users,  load average: 0.00, 0.00, 0.00 02:50:15 up 1 day, 11:47,  3 users,  load average: 0.00, 0.00, 0.00

Method Two: Append to log log file

[[email protected] jiaobenlianxi]# cat while2.sh #!/bin/shwhile [ 1 ]   do    uptime >>./uptime.log    sleep 2   done

Tips:

[[email protected] jiaobenlianxi]# sh while2.sh &[1] 3991

In the background for permanent execution, we call it daemon mode.

[[email protected] jiaobenlianxi]# tail -f uptime.log  03:00:24 up 1 day, 11:57,  3 users,  load average: 0.01, 0.01, 0.00 03:00:26 up 1 day, 11:57,  3 users,  load average: 0.01, 0.01, 0.00

Ways to prevent client execution of script interrupts

(1) SH while2.sh & plus & symbol

(2) Nohup while2.sh &

(3) Screen hold session

1.2.2 Scripts perform knowledge extensions in the background

Extended Data:

BG: Running in the background

FG: Suspending Program

Jobs: Show Background programs

Kill,killall,pkill: Kill the process

Crontab: Set Timing

PS: View Process

Pstree: Show Process

Nice: Change the priority level

Nohup: The user continues to work after exiting the system

Pgrep: Finding the process for matching criteria

STRACE: Tracking the system call situation of a process, if in the work of a process usage is too high can use Strace to see the process system call situation, if not understand can let development to see.

Itrace: The case in which the trace process calls the library function.

Vmstat: Reports virtual memory statistics.

1.3 Simple Example 1.3.1 Example 1: Computes the and from 1 to 100 by using the while statement, using the 1+2+3 method
[[email protected] jiaobenlianxi]# cat 1-100.sh #!/bin/shsum=0i=1while [ $i -le 100 ]do ((sum=sum+i)) ((i++))doneecho $sum
1.3.2 Example 2: The results calculated by the mathematical formula below
[[email protected] jiaobenlianxi]# cat sum1-100.sh #!/bin/shi=100((sum=i*(i+1)/2))echo $sum

More implementations 1 to 100 and please read the old boy's teacher's blog post.

http://blog.51cto.com/oldboy/767862

1.3.3 Example 3:

Mobile phone recharge 10 yuan, every text message (output current balance) cost 1.5 cents, when the balance is less than 1.5 cents money can not send text messages, indicating insufficient balance, please recharge (you can allow users to continue to recharge and continue to send text messages), please use while statement implementation.

Hint: unit conversion, unified unit, unified into integers. 10 Yuan = 1000 points, 1.5 cents = 15 points

[[email protected] jiaobenlianxi]# cat huafei.sh #!/bin/bashhuafei=100yue=25if [-f/etc/init.d/functions];then . /etc/init.d/functionsfioption () {case ' $option ' in [yy]|[        YY][EE][SS]) echo "Send a Success" Echo $txt >>/var/log/consum.log ((Huafei=huafei-yue))    echo "You ' re still saving money $HUAFEI";; [nn]| [NN]        [OO])        echo "Abort send, succeed."        ;; *) echo "Input error" Esac return 0}change1 () {expr $change + 1 &>/dev/null if ["$?"-ne "0"-a "$    Change "! ="-1 "];then echo" there is illegal characters, please reenter the amount of recharge. " Else break fi return 0}change () {and truedoread-p "Please input the amount you want to recharge:" Changechange 1donereturn 0}change2 () {(Huafei+=change) echo "You" re still saving money $HUAFEI "}option2 () {case" $option 2 "in [yy]| [YY] [EE]        [SS])    Change CHANGE2;; [nn]| [NN]        [OO])   Exit 1;;     *) echo "Input error, please enter the correct amount." Change Change2esacreturn 0}linzhongniao () {if ["$HUAFEI"-lt "$YUE"];then read-p "the balance is insufficient, p Lease Recharge[y|n] "Option2 option2fireturn 0}main () {While [" $HUAFEI "-ge" $YUE "]doread-p" Please enter the Conten T of the text message: "Txtread-p" Confirm send [Y|n] "Optionoptionlinzhongniaodonereturn 0}main
1.4 Extensions

While reading a file by line

1.4.1 Method One
[[email protected] jiaobenlianxi]# cat while_duwenjian1.sh #!/bin/bashexec <nginx.shsum=0while read linedo    cmddone
1.4.2 Method Two
[[email protected] jiaobenlianxi]# cat while_duwenjian2.sh #!/bin/bashcat ${FILE_PATH}|while read linedo    cmddone
1.4.3 Method Three
[[email protected] jiaobenlianxi]# cat while_duwenjian3.sh #!/bin/bashwhile read linedo    cmddone<FILE
1.4.4 Problem Analysis Apache Log example

Calculates the sum of the number of bytes of access to log elements for all rows in the log access_2010-12-8.log of the Apache day. Integrated implementation program. Practice log: See the directory under Access_2012-12-8.log, you can also use your own Apache log, use the while statement implementation.

[[email protected] jiaobenlianxi]# cat while3.sh #!/bin/bashexec < /etc/httpd/logs/access_logwhile read linedo    i=echo $line|awk ‘{print $10}‘    expr $i + 1 &>/dev/null    if [ $? -ne 0 ];then    continue    fi    ((sum+=1))done[ -n "$sum" ] && echo $sum
2.While Cycle Summary

The advantage of the A.while loop is that the daemon is executed and we want the loop not to exit continuous execution, for frequencies less than one minute of cyclic processing (crond), and the other while loops can be replaced almost by a for loop.

The B.case statement can replace an if statement, typically passing a small number of fixed-rule strings in a system startup script, with a case statement. Other common judgments are multiple if statements.

The c.if and for statements are most commonly used, followed by the while (daemon), Case (service startup script).

Application scenarios for each statement:

conditional expressions, simple judgments (whether the file exists, whether the string is empty, and so on).

If the value is judged, the number of different values is less.

For Normal loop processing, most commonly used!

While daemon, Infinite loop (sleep).

Case service startup script, menu.

The function logic is clear and the repeating statement is reduced.

Shell Script Programming Learning notes-while loops

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.