Examining the many ways to run loops on Linux

You could use a loop like those shown below to run through the letters of the alphabet or a sequence of numbers.

$ for x in {a..z}
do
    echo $x
done

$ for x in {1..11}; do     echo $x; done

The for command below would display calendars for the last three months of the current year.

$ year=`date +%Y`; for month in {10..12}; do cal $month $year;  done

The script below loops through all the months of the year.

$ for month in `locale mon | sed 's/;/ /g'`; do   echo $month; done
January
February
March
April
May
June
July
August
September
October
November
December

Using while loops

While loops keep looping as long as the condition that they’re set up to monitor is true. Here’s an example:

#!/bin/bash

n=1

while [ $n -le 4 ]
do
    echo $n
    ((n++))
done

The script above increments and displays the value of $n as long as it’s less than or equal to 4. You can get a while loop to run forever (i.e., until the system crashes, you log out, or someone kills your script) using “while true” as shown below. The sleep command ensures that it doesn’t run thousands of times before you have a chance to stop it.

#!/bin/bash

while true
do
    echo -n "Still running at "
    date
    sleep 10
done

The script below will run as long as the user who it’s waiting for has not yet logged into the system. This can be helpful when you’re waiting for a co-worker to address a problem before you can move ahead with your task. It checks once a minute to see if the user has logged in yet.



Source link

Leave a Comment