Home  >  Article  >  Operation and Maintenance  >  Using while loop in bash shell script

Using while loop in bash shell script

不言
不言Original
2019-03-22 13:23:194463browse

Similar to the for loop, the while loop is also a loop with restrictive conditions at the beginning. This means that the condition needs to be checked before executing the while loop. Most of the time it can also do everything a for loop can do, but it has its own advantages in programming.

Using while loop in bash shell script

Syntax:

while [ condition ]
do
// 执行
done

while loop example in bash

For example, when the value of i is greater than 10, the following loop will be executed 10 times and exit.

#!/bin/bashi=1
while [$i-le10]
do
   echo "This is looping number $i"
   leti++done

while infinite loop in bash

The infinite for loop is also a never-ending loop. The loop will continue executing until forced to stop using ctrl-c.

#!/bin/bash

whiletruedo
  echo "Press CTRL+C to Exit"
done

But we can also use conditional statements like if to terminate the loop when a specific condition is matched.

#!/bin/bash

whiletruedo
   if [ condition ];do
      exit
   fi
done

In bash script, we can also write a while loop similar to C language.

#!/bin/bash

i=1
while((i <= 10))
do
   echo $i
   let i++
done

Use a while loop to read the file content

The while loop also provides the option to read the file content line by line, which is very useful when the while loop is processing files usage.

#!/bin/bash

while read i
do
   echo $i
done < /tmp/filename.txt

In this while loop, one line is read from the file in one loop and the value is stored in the variable i.

This article has ended here. For more other exciting content, you can pay attention to the Linux Tutorial Video column on the PHP Chinese website!

The above is the detailed content of Using while loop in bash shell script. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn