While Loop
Sure, I can help you learn about the while
loop in shell scripting! The while
loop in shell scripting repeatedly executes a set of commands as long as a given condition is true.
Here's the basic syntax for a while
loop in a shell script:
while [ condition ]
do
# commands to be executed
done
Let's go through an example to understand how it works. Suppose you want to create a script that prints numbers from 1 to 5.
Example Script: Printing Numbers from 1 to 5
- Open a text editor and create a new file, e.g.,
example.sh
. - Add the following code to the file:
#!/bin/bash
# Initialize a variable
counter=1
# Start the while loop
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++)) # Increment the counter
done
Example 2: Reading a File Line by Line
#!/bin/bash
# Initialize a file variable
file="sample.txt"
# Start the while loop
while IFS= read -r line
do
echo "$line"
done < "$file"
In this script, IFS= read -r line
reads each line from the file sample.txt
and stores it in the variable line
, which is then printed.
IFS stands for "Internal Field Separator" in Unix and Linux shell scripting. It is an environment variable that defines the characters used by the shell to split a line of text into words or tokens. By default, IFS includes the space, tab, and newline characters.
Comments
Post a Comment