Linux Shell Scripting : LOOPS

Linux Shell Scripting : LOOPS

What is Shell Scripting?

Shell scripting refers to writing scripts or programs that are interpreted and executed by a shell, which is a command-line interpreter for operating systems like Unix, Linux, and macOS. The shell is an interface between the user and the operating system, allowing users to execute commands and perform various tasks.

A shell script is a text file containing a series of commands written in a scripting language specific to the shell being used, such as Bash (Bourne Again SHell) or C Shell (csh). These scripts can automate repetitive tasks, perform system administration tasks, or combine multiple commands into a single script for more complex operations.

Loops

In Linux shell scripting, loops are used to execute a set of commands repeatedly. They allow you to automate repetitive tasks and process data efficiently. There are mainly two types of loops used in shell scripting: the for loop and the while loop.

Both for and while loops can be used in combination with conditional statements (if statements) and control flow statements (break and continue) to provide more complex logic within the loop.

For Loop

The for loop iterates over a sequence of values and performs a set of commands for each value in the sequence.

Here's the syntax for a for loop in shell scripting:

for variable in sequence

do

# Commands to be executed

done

Creating Shell Script

  • Create a file using the command touch.

  • Use the file extension (.sh).

  • To edit the file use the command vi with file name.

  • Write the shebang at the top.

  • We will use the syntax with the condition.

  • Write the condition in which you want to be looped.

  • Use the do to use the echo command which will print our result.

  • At the end write done to close the for loop.

  • Use the bash command with the file name to Run the Shell Script.

  • Below you can see the results.

While Loop

The while loop executes a set of commands repeatedly as long as a certain condition is true.

Here's the syntax for a while loop in shell scripting:

while condition

do

# Commands to be executed

done

Creating Shell Script

In this example, the loop continues until the value of the counter variable becomes greater than 5. The counter variable is incremented by 1 in each iteration.