Click on each book below to review & buy on Amazon.
As an Amazon Associate, I earn from qualifying purchases.
LPI Linux Essentials Exam 010-160 - Topic 3.3 - Mastering Loops: FOR, UNTIL & WHILE
Within the Linux environment, the ability to iterate over sets of commands and data is a fundamental concept for automating repetitive tasks. The constructs for
, until
, and while
offer distinct ways to cycle through loops, each serving specific use cases in shell scripting. Understanding their syntax and application empowers a user to efficiently handle batch processing and automate system tasks with precision.
Exploring the For Loop
The for
loop is a versatile tool for traversing a sequence of items, such as strings, numbers, or file contents. Its syntax is elegantly straightforward, which allows it to be used with ease in many scenarios. Here's how you can write a basic for
loop in a bash script:
for item in sequence
do
# Actions to be performed on each item
done
In this construction, the sequence
is the collection of items you wish to iterate over. During each iteration, the item
variable captures the current element, which you can manipulate or use within the body of the loop, demarcated by do
and done
.
Practical Application: Processing Directories
Imagine a situation where you need to comb through several directories, searching for files exceeding a certain size threshold. With a for
loop, you can seamlessly glide through each directory and perform the check:
for dir in /usr/share/doc /var/log /etc
do
find $dir -type f -size +500k -exec ls -lh {} \;
done 2> /dev/null
In this snippet, the find
command systematically inspects each directory specified in the list, searching for files larger than 500K. The -type f
flag restricts the search to files, while -exec ls -lh {} \;
executes a detailed list command on each file that meets the criteria. By redirecting errors to /dev/null
, the output is kept clean, showing only the successful listings.
Service Status Inquiry
When managing system services, a for
loop can be employed to query the status of each service in a list, providing a batch status report:
for service in sshd dbus rsyslog
do
systemctl --no-pager status $service
done
This loop runs the systemctl status
command on a trio of essential services (sshd
, dbus
, rsyslog
), yielding their operational status in sequence, thus streamlining system checks into a simple, repetitive task.
Delving into the Until Loop
In contrast to the for
loop, the until
loop continues execution until the provided condition evaluates to true. This loop is particularly useful when the termination condition is easier to define than the continuation condition. The basic structure of an until
loop looks like this:
until [ condition ]
do
# Commands to execute until the condition is met
done
Here, the condition
is evaluated before each iteration, and the commands within the do
and done
block are executed so long as the condition remains false. Once the condition is satisfied, the loop ceases to execute.
Counting to Five
An example of the until
loop in action could be a simple counter that prints numbers incrementally:
counter=1
until [ $counter -gt 5 ]
do
echo $counter
sleep 1
(( counter++ ))
done
The variable counter
begins at 1 and the loop runs until it increments to a value greater than 5. Each iteration pauses for a second (thanks to sleep 1
), allowing for a time-staggered output.
File Existence Monitoring
Consider a scenario where you need to wait until a file is removed before proceeding. The until
loop is perfectly suited for this task:
touch /tmp/remove_me.txt
until [ ! -f /tmp/remove_me.txt ]
do
echo "Waiting for removal of /tmp/remove_me.txt - timestamp: $(date)"
sleep 5
done
In this case, the loop continually checks for the non-existence of /tmp/remove_me.txt
. It prompts the user at regular intervals, allowing another process or user to remove the file as required for the loop to terminate.
The While Loop
The while
loop offers yet another looping mechanism, with the distinction that it continues as long as the given condition is true. This is useful in cases where you need to execute a set of commands indefinitely or until a certain state changes. A while
loop's syntax is as follows:
while [ condition ]
do
# Commands to execute while the condition is true
done
In every while
loop, the condition
is evaluated before each iteration, and if it holds true, the commands between do
and done
are executed. When the condition fails, the loop exits.
Iterative Counting
Similar to the until
loop, you can use a while
loop to count from 1 to 5, only this time the condition keeps the loop running as long as the counter is less or equal to 5:
counter=1
while [ $counter -le 5 ]
do
echo $counter
sleep 1
(( counter++ ))
done
Each pass through the loop prints the current count, waits a moment, and then increments the counter. When the counter exceeds 5, the loop concludes.
Processing File Contents
When faced with the need to read through a file line by line, while
combined with read
is a potent combination:
while IFS= read -r line
do
if echo $line | grep -q '/sbin/nologin'; then
echo "No login shell found: $line"
fi
done < /etc/passwd
In this example, the script reads from /etc/passwd
and passes each line to the loop. Inside the loop, it searches for lines that contain /sbin/nologin
, indicating an account with a disabled login shell. The use of grep -q
quietly checks for the presence of the string, only producing output when a match is found.
Tip
Setting IFS=
with no value followed by read
command, as in IFS= read -r line
, changes the behavior of the read built-in bash command. It tells read
to consider the entire line as a single field and to not split it up into different fields based on the presence of spaces, tabs, or other IFS
characters. This is particularly useful when reading lines that contain spaces or tabs that you do not want to be interpreted as field separators.
The careful design of these loops in shell scripts is integral to the smooth and automated functioning of many routine Linux tasks. Whether deploying scripts for administrative purposes or batch processing, the correct use of for
, until
, and while
loops will significantly streamline and enhance your shell scripting endeavors.
Support DTV Linux
Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.
NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.