Shell Script While Loop Examples

www.laut‮.irut‬com
Shell Script While Loop Examples

A while loop in a shell script allows you to execute a block of commands repeatedly as long as a certain condition is met.

Here are some examples of while loops in a shell script:

# Print numbers from 1 to 10
i=1
while [ $i -le 10 ]
do
  echo $i
  i=$((i+1))
done

This will print the numbers from 1 to 10 to the console. The while loop will run as long as the value of the $i variable is less than or equal to 10. The $((i+1)) expression will increment the value of the $i variable by 1 at the end of each iteration.

# Read lines from a file and print them to the console
while read line
do
  echo $line
done < file.txt

This will read lines from the file.txt file and print them to the console. The while loop will run as long as there are lines to read from the file. The read command will read a line from the file and assign it to the $line variable at the beginning of each iteration.

# Check if a process is running and restart it if it is not
while true
do
  if ! pgrep process > /dev/null
  then
    start process
  fi
  sleep 60
done

This will check if the process is running and restart it if it is not. The while loop will run indefinitely as long as the true command always returns a successful exit status. The if statement will use the pgrep command to check if the process is running and the ! operator to invert the result. If the process is not running, the start command will be executed to start it. The sleep command will pause the script for 60 seconds at the end of each iteration.

Keep in mind that these are just a few examples of while loops in a shell script. You can customize the conditions, commands, and variables to meet the specific requirements of your script. You should also regularly review and update the script to ensure that it is correct and efficient.

Created Time:2017-10-30 14:27:18  Author:lautturi