A Bash Script: A while loop in the Loop Structure

Source: Internet
Author: User

A Bash Script: A while loop in the Loop Structure

Like other languages, the Bash loop structure also contains the while statement.

Basic Structure
While condition do loop body done

Like the for statement, its loop body is also do... Done structure. We can fold the while statement.

While condition; do loop body done

It can be further folded into a row

While condition; do loop body; done

Most Bash statements can write one line, but the readability is poor.

Unlike other programming languages, the while statement usage in Bash is diverse. You can divide the while statement into several classes based on the while condition.

While Condition Square brackets []

The condition is the same as that of the if statement. That is, the operator []. For [] usage, refer to the previous article.

#! /Bin/bashn = 1 while [$ n-le 10] do echo $ n let n ++ # Or write n = $ ($ n + 1) done

In the previous article, we have already mentioned that the operator [] is equivalent to the test statement, so here we can use the test statement as the condition.

Terminal commands

The while condition can be the commands of various terminals. Including external commands or bash built-in (built-in) commands. Because all commands return values (you can use echo $? Check). Whether the command execution is successful is the true or false of the while condition.

Here is an example using the read command.

#! /Bin/bashwhile read var; do echo "$ var" done

This program is an endless loop that will keep waiting for your input and display it back.

The command can be a single command or a combination of commands, such as a command connected with a logical connector, or a long command composed of pipelines and redirection.

Endless loop

In addition to keeping the while condition unchanged, programming languages all have a concise method of endless loops. For example, in C language, the typical infinite loop condition is while (1), while in java, the statement is while (true ).
In Bash, many write rules are simple, and only one colon is required.

#!/bin/bashwhile :do echo I love you foreverdone

This is an endless loop. After execution, press Ctrl + C to terminate it.
In addition, an endless loop is written by using the true command (/bin/true) that comes with the system)

#!/bin/bashwhile /bin/truedo echo I love you foreverdone

Because our system environment variables (PATH) generally contain paths/bin, we can also abbreviated them to while true.

While implementation menu demo

We may have used C/C ++ to output menus on the console. This is usually implemented by a do-while loop. First, each option of the menu is output, and then wait for the input,
Execute different operations based on different inputs, and then output the menu again .......
Bash does not have a do-while loop, but we can easily implement this function using an alternative solution. It is enough to use an endless loop + if/case condition to determine the statement.

#! /Bin/bash # menu demowhile: do echo # output empty line echo "========================" echo "1: output transcript "echo" 2: Output course schedule "echo" 3: Output idle classroom "echo" q: to exit the menu, enter: "input case $ input in 1) echo" Wait, output transcript "; 2) echo" Wait, output course schedule for you "; 3) echo" wait, "; q | Q) exit esacdone
While and redirection

The while statement can be used together with redirection (> and <.

While and input redirection <

Format:

While command do loop body done <file name

It is equivalent to passing the file content line by line to the Command (similar to the pipeline) after while, and then executing the loop body.
When the loop body is empty, the function of this structure is usually the same as cat, for example:

while grep "love"dodone < letter

Finding the word "love" in the file letter is actually no different from cat letter | grep "love.

This structure is used in combination with read to retrieve the file content row by row and assign the value to the variable after read. For example:

#! /Bin/bash # Read the username from the/etc/passwd file and output oldIFS = $ IFS # IFS is the internal delimiter of the file IFS = ":" # Set the delimiter: while read username var # var variable do echo "username: $ username" done </etc/passwd IFS = $ oldIFS

Anyone familiar with the/etc/passwd file structure knows that each row of the file contains a large amount of information about the user (the user name is only the first item ).
Here, we only output the user name. However, note that there is a var after the while read except the username variable, even though we do not output the value of this variable.
But it is essential. If we write while read username, then the username value is equal to the whole line of the passwd file (IFS = ":" Does not work)

In bash, only when multiple variables need to be assigned a value from a line of text, try to use IFS for segmentation and then assign values.

While and output redirection>

Format:

While command do loop body done> file name

This structure redirects the command output and the standard output in the loop body to the specified file.
For example:

#! /Bin/Basho every 10 minutes, pingw.local network hosts 192.168.1.101. then, the final result is recorded in the ping.txt file while datedo ping-c5 192.168.1.101>/dev/null 2> & 1 if [$? = 0]; then echo OK else echo FAIL fi sleep 600 #600 seconds is 10 minutes done> ping.txt

Let's take a look at the cat ping.txt file:

Saturday, January 31, 2015 16:03:13 CSTOK

This is a record in ping.txt.

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.