BASH For Loop Examples

28/12/2020
Loops are used in any programming language to execute the same code repeatedly. Three types of loops are mainly used in programming for doing repetitive tasks. These are for, while and do-while/repeat-until loop. You can apply for loop on bash script in various ways. Some useful BASH for loops examples are mentioned in this article.

Syntax of for loop:

for variable_name in lists
do
commands
done

The starting and ending block of for loop are defined by do and done keywords in bash script. How many times a for loop will iterate depends on the declared lists variable. The loop will take one item from the lists and store the value on a variable which can be used within the loop. The use of different types of bash for loops example are explained below. Open a text editor to test the following code examples.

Example-1: Reading static values

Create a bash file named loop1.sh which contains the following script.

for color in Blue Green Pink White Red
do
echo "Color = $color"
done

In this example, 5 static values are declared in the lists part. This loop will iterate 5 times and each time It will receive a value from the lists and store it in the variable named color which will print inside the loop. The following output will appear if you run loop1.sh.

Example-2: Reading Array Variable

You can use for loop to iterate the values of an array. Create a new bash file named loop2.sh with the following code.

ColorList=("Blue Green Pink White Red")
for color in $ColorList
do
if [ $color == ‘Pink’ ]
then
echo "My favorite color is $color"
fi
done

In this example, the loop retrieves the values from an array variable named ColorList and it will print the output only if Pink value is found in the array elements.

Example-3: Reading Command-line arguments

Command-line arguments values can be iterated by using for loop in bash. Create a new bash file named loop3.sh with the following code.

for myval in $*
do
echo "Argument: $myval"
done

The following output will appear after running the script. Three arguments are given as command-line arguments in this example. These are ‘I’, ‘like’ and ‘Programming’

Example-4: Finding odd and even number using three expressions

The most common syntax of for loop is three expression syntax. First expression indicates initialization, second expression indicates termination condition and third expression indicates increment or decrement. Create a new file named loop4.sh to check the script.

for (( n=1; n<=5; n++ ))
do
if (( $n%2==0 ))
then
echo "$n is even"
else
echo "$n is odd"
fi
done

The loop will iterate for 5 times from the value 1 to 5 and it will check and print even and odd numbers. You will get the following output after executing the script.

Example-5: Reading file content

You can use for loop to read content of any file by using ‘cat’ command. Suppose, you have a file named ‘weekday.txt’ which contains the name of all week days. Now, create a bash file named loop5.sh to read the content of the file.

i=1
for var in `cat weekday.txt`
do

echo "Weekday $i: $var"
((i++))
done

The following output will appear after running the script.

By using for loop, in bash, you can traverse data from different sources and different ways and become more productive on the terminal or in your scripts.  Check out the related video below:

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Read filename without extension in Bash

Linux users need to work with files regularly for many purposes. Sometimes the users need to read the basename of the file...
29/12/2020

Bash base64 encode and decode

To encode or decode standard input/output or any file content, Linux uses base64 encoding and decoding system. Data are...
29/12/2020

BASH command output to the variable

Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024

Thuê địa chỉ IPv4 IPv6 trọn gói ở đâu chất lượng, giá RẺ nhất?
27/05/2024