Conditional Expressions
Numerical Comparison:
The numerical comparison operators used in the “while” loop condition are:
-eq
: Equal to-ne
: Not equal to-gt
: Greater than-ge
: Greater than or equal to-lt
: Less than-le
: Less than or equal to
Example:
while [ $var -lt 10 ]
- This loop will continue as long as the value of the variable
$var
is less than 10.
String Comparison:
The string comparison operators used in the “while” loop condition are:
=
: Equal to!=
: Not equal to
Example:
while [ "$var" != "stop" ]
- This loop will continue as long as the value of the variable
$var
is not equal to the string “stop”.
It’s important to use double quotes around the variable to ensure that it is properly evaluated, even if it contains spaces or other special characters.
File Existence:
The file existence operators used in the “while” loop condition are:
-f
: File exists and is a regular file-d
: File exists and is a directory-e
: File exists (regardless of type)
Example:
while [ -f "/path/to/file" ]
- This loop will continue as long as the file “/path/to/file” exists and is a regular file.
Command Execution:
You can also use the output of a command as the condition for a “while” loop.
Example:
while grep -q "pattern" file.txt
- This loop will continue as long as the
grep
command finds the specified “pattern” in the file “file.txt”.
The -q
option in the grep
command makes it “quiet”, meaning it will only return a success or failure exit status, without printing any output.
These are just a few examples of the common conditional expressions that can be used in a “while” loop. The shell supports a wide range of operators and expressions that can be used to create more complex and flexible loop conditions.
while Command in Linux with Example
The “while” command is a powerful tool in the Linux shell that allows you to execute a series of commands repeatedly based on a given condition. It is commonly used in shell scripts to create loops, where a block of code is executed as long as a particular condition remains true.