国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home System Tutorial LINUX How to Use Bash For Loop in Linux: A Beginner's Tutorial

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Jun 17, 2025 pm 03:20 PM

In programming languages, Loops are essential components and are used when you want to repeat code over and over again until a specified condition is met.

In Bash scripting, loops play much the same role and are used to automate repetitive tasks just like in programming languages.

In Bash scripting, there are 3 types of loops: for loop, while loop, and until loop. The three are used to iterate over a list of values and perform a given set of commands.

In this guide, we will focus on the Bash For Loop in Linux.

Table of Contents

Bash For Loop Syntax

As mentioned earlier, the for loop iterates over a range of values and executes a set of Linux commands.

For loop takes the following syntax:

for variable_name in value1 value2 value3  .. n
do
    command1
    command2
    commandn
done

Let us now check a few example usages of the bash for loop.

Bash For Loop Example

In its simplest form, the for loop takes the following basic format. In this example, the variable n iterates over a group of numerical values enclosed in curly braces and prints out their values to stdout.

for n in {1 2 3 4 5 6 7};
do
   echo $n
done

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Bash For Loop with Ranges

In the previous examples, we explicitly listed the values to be iterated by the for loop, which works just fine. However, you can only imagine how cumbersome and time-consuming a task it would be if you were to iterate over, for example, a hundred values. This would compel you to type all the values from 1 to 100.

To address this issue, specify a range. To do so, specify the number to start and stop separated by two periods.

In this example, 1 is the first value whilst 7 is the last value in the range.

#!/bin/bash

for n in {1..7};
do
   echo $n
done

Once the shell script is executed, all the values in the range are listed, similar to what we had in simple loops.

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Additionally, we can include a value at the end of the range that is going to cause the for loop to iterate through the values in incremental steps.

The following bash script prints the values between 1 and 7 with 2 incremental steps between the values starting from the first value.

#!/bin/bash

for n in {1..7..2};
do
   echo $n
done

How to Use Bash For Loop in Linux: A Beginner's Tutorial

From the above example, you can see that the loop incremented the values inside the curly braces by 2 values.

Bash For Loops with Arrays

You can also easily iterate through values defined in an array using a for Loop. In the following example, the for loop iterates through all the values inside the fruits array and prints them to stdout.

#!/bin/bash

fruits=("blueberry" "peach" "mango" "pineapple" "papaya") 

for n in ${fruits[@]}; 
do
    echo $n
done

How to Use Bash For Loop in Linux: A Beginner's Tutorial

The @ operator accesses or targets all the elements. This makes it possible to iterate over all the elements one by one.

In addition, you can access a single element by specifying its position within the array.

For example to access the “mango” element, replace the @ operator with the position of the element in the array (the first element starts at 0, so in this case, “mango” will be denoted by 2).

This is what the for loop looks like.

#!/bin/bash

fruits=("blueberry" "peach" "mango" "pineapple" "papaya") 

for n in ${fruits[2]}; 
do
    echo $n
done

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Bash C Style For Loop

You can use variables inside loops to iterate over a range of elements. This is where C-styled for loops come in. The following example illustrates a C-style for loop that prints out a list of numerical values from 1 to 7.

#!/bin/bash

n=7
for (( n=1 ; n
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175014481977280.jpg" class="lazy" alt="How to Use Bash For Loop in Linux: A Beginner's Tutorial"></p>
<h2>
<span class="ez-toc-section" id="Bash_C-styled_For_Loops_With_Conditional_Statements"></span>Bash C-styled For Loops With Conditional Statements<span class="ez-toc-section-end"></span>
</h2>
<p>You can include conditional statements inside <strong>C-styled for loops</strong>. In the following example, we have included an if-else statement that checks and prints out even and odd numbers between 1 and 7.</p>
<pre class="brush:php;toolbar:false">#!/bin/bash

for (( n=1; n
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175014482016912.jpg" class="lazy" alt="How to Use Bash For Loop in Linux: A Beginner's Tutorial"></p>
<h2>
<span class="ez-toc-section" id="Use_the_‘Continue_statement_with_Bash_For_Loop"></span>Use the ‘Continue’ statement with Bash For Loop<span class="ez-toc-section-end"></span>
</h2>
<p>The ‘<strong>continue</strong>‘ statement is a built-in command that controls how a script runs. Apart from bash scripting, it is also used in programming languages such as Python and Java.</p>
<p>The <strong>continue statement</strong> halts the current iteration inside a <strong>loop</strong> when a specific condition is met, and then resumes the iteration.</p>
<p>Consider the <strong>for loop</strong> shown below.</p>
<pre class="brush:php;toolbar:false">#!/bin/bash
for n in {1..10}
do
        if [[ $n -eq '6' ]]
        then
              echo "Target $n has been reached"
              continue
        fi
        echo $n
done

How to Use Bash For Loop in Linux: A Beginner's Tutorial

This is what the code does:

  • Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
  • Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and restarts the loop at the next iteration in line 2.
  • Line 9: Prints the values to the screen only if the condition in line 4 is false.

The following is the expected output after running the script.

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Use the ‘break’ statement with Bash For Loop

The ‘break’ statement, as the name suggests, halts or ends the iteration when a condition is met.

Consider the For loop below.

#!/bin/bash
for n in {1..10}
do
        if [[ $n -eq '6' ]]
        then
                echo "Target $n has been reached"
                break
        fi
        echo $n
done
echo "All done"

How to Use Bash For Loop in Linux: A Beginner's Tutorial

This is what the code does:

  • Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
  • Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and halts the iteration.
  • Line 9: Prints the numbers to the screen only if the condition in line 4 is false.

From the output, you can see that the loop stops once the variable meets the condition of the loop.

How to Use Bash For Loop in Linux: A Beginner's Tutorial

Conclusion

That was a tutorial about Bash For loops. We hope you found this insightful. Feel free to weigh in with your feedback.

The above is the detailed content of How to Use Bash For Loop in Linux: A Beginner's Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a new, empty file from the command line? How to create a new, empty file from the command line? Jun 14, 2025 am 12:18 AM

There are three ways to create empty files in the command line: First, the simplest and safest use of the touch command, which is suitable for debugging scripts or placeholder files; Second, it is quickly created through > redirection but will clear existing content, which is suitable for initializing log files; Third, use echo"> file name to create a file with an empty string, or use echo-n""> file name to avoid line breaks. These three methods have their own applicable scenarios, and choosing the right method can help you complete the task more efficiently.

5 Best Open Source Mathematical Equation Editors for Linux 5 Best Open Source Mathematical Equation Editors for Linux Jun 18, 2025 am 09:28 AM

Are you looking for good software to write mathematical equations? If so, this article provides the top 5 equation editors that you can easily install on your favorite Linux distribution.In addition to being compatible with different types of mathema

SCP Linux Command – Securely Transfer Files in Linux SCP Linux Command – Securely Transfer Files in Linux Jun 20, 2025 am 09:16 AM

Linux administrators should be familiar with the command-line environment. Since GUI (Graphical User Interface) mode in Linux servers is not commonly installed.SSH may be the most popular protocol to enable Linux administrators to manage the servers

How to Install Eclipse IDE in Debian, Ubuntu, and Linux Mint How to Install Eclipse IDE in Debian, Ubuntu, and Linux Mint Jun 14, 2025 am 10:40 AM

Eclipse is a free integrated development environment (IDE) that programmers around the world use to write software, primarily in Java, but also in other major programming languages using Eclipse plugins.The latest release of Eclipse IDE 2023?06 does

24 Hilarious Linux Commands That Will Make You Laugh 24 Hilarious Linux Commands That Will Make You Laugh Jun 14, 2025 am 10:13 AM

Linux has a rich collection of commands, and while many of them are powerful and useful for various tasks, there are also some funny and whimsical commands that you can try out for amusement. 1. sl Command (Steam Locomotive) You might be aware of the

Install LXC (Linux Containers) in RHEL, Rocky & AlmaLinux Install LXC (Linux Containers) in RHEL, Rocky & AlmaLinux Jul 05, 2025 am 09:25 AM

LXD is described as the next-generation container and virtual machine manager that offers an immersive for Linux systems running inside containers or as virtual machines. It provides images for an inordinate number of Linux distributions with support

What is a PPA and how do I add one to Ubuntu? What is a PPA and how do I add one to Ubuntu? Jun 18, 2025 am 12:21 AM

PPA is an important tool for Ubuntu users to expand their software sources. 1. When searching for PPA, you should visit Launchpad.net, confirm the official PPA in the project official website or document, and read the description and user comments to ensure its security and maintenance status; 2. Add PPA to use the terminal command sudoadd-apt-repositoryppa:/, and then run sudoaptupdate to update the package list; 3. Manage PPAs to view the added list through the grep command, use the --remove parameter to remove or manually delete the .list file to avoid problems caused by incompatibility or stopping updates; 4. Use PPA to weigh the necessity and prioritize the situations that the official does not provide or require a new version of the software.

Gogo - Create Shortcuts to Directory Paths in Linux Gogo - Create Shortcuts to Directory Paths in Linux Jun 19, 2025 am 10:41 AM

Gogo is a remarkable tool to bookmark directories inside your Linux shell. It helps you create shortcuts for long and complex paths in Linux. This way, you no longer need to type or memorize lengthy paths on Linux.For example, if there's a directory

See all articles