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

Bash builtin examples

builtin candidate_builtin arg … in bash allows you to only call bash builtins. That is, even if an external command or...
29/12/2020

How to debug a bash script?

A script is just a file containing a set of commands. The basic idea of a script is to automatically execute and re-execute...
29/12/2020

Bash Range: How to iterate over sequences generated on the shell

You can iterate the sequence of numbers in bash by two ways. One is by using seq command and another is by specifying range...
28/12/2020
Bài Viết

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

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024