• Latest
  • Trending
How to Use Arrays in a Bash Script

How to Use Arrays in a Bash Script

April 11, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

How to Use Arrays in a Bash Script

by ITECHNEWS
April 11, 2022
in Data Science, Leading Stories
0 0
0
How to Use Arrays in a Bash Script

Like most programming languages, bash scripts sometimes need to deal with a list of related values. The simplest form is the standard array.

In bash, array programming is quite different, in particular when it comes to syntax. Bash arrays are also strictly one-dimensional, but they still have plenty of uses.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

The Basic Syntax of Bash Arrays

Creating an array in bash is straightforward. You can initialize an entire array using brackets, for example:

city=(London Paris Milan "New York")

(You can find all the code from this city example in this GitHub Gist.)

This creates an array containing four elements, indexed from 0 to 3. Note that the fourth value is a quoted string consisting of two words. You’ll need to quote values containing spaces to clarify that they aren’t separate values.

You can access a single element using the bracket syntax that’s common across programming languages:

city[2]

Since this is bash, you’ll need a couple of refinements to actually use the value in an expression:

  • You’ll need to prepend the dollar sign ($) to the variable name.
  • You’ll also need to use braces ({}) to make the variable name unambiguous. By default, bash will treat $city[2] as a variable named city. Add braces to tell bash to evaluate the brackets and index number too.

The standard bash array access syntax is then:

${variable_name[index]}

Here’s a complete example:

#!/bin/bash
 
city=(London Paris Milan "New York")
echo ${city[3]}
 
# New York

Instead of initializing an array all at once, you can assign to it step-by-step. This script is a longer equivalent of the previous example:

#!/bin/bash
 
city[0]=London
city[1]=Paris
city[2]=Milan
city[3]="New York"
echo ${city[3]}
 
# New York

Note that, in either case, you need to be careful not to add any space around the equals sign. “city[0] = London”, with spaces around the equals sign, will generate an error.

More Uses for Bash Arrays

Arrays are perfect for storing related data. Here’s a (very limited) shell script to get the square root of a number:

#!/bin/bash
 
sqrt[1]=1
sqrt[4]=2
sqrt[9]=3
sqrt[16]=4
sqrt[25]=5
 
echo ${sqrt[$1]}

Note that the script uses the value $1 as the array index. $1 represents the first command-line argument the script receives, so you can run this script like so:

$ ./sqrt.sh 9
3

You may be aware of the $(cmd) syntax to execute a command and save its output in a variable. You can combine this with the array initialization syntax to get an array of files to work with:

arr=( $(ls) )

An array is often a perfect data structure for iterating and Bash is no exception. You might loop through an array to print every element or to perform an operation on every member.

You can address an array in a for .. in loop, to iterate over its contents. For example, here’s a simple loop that prints the number of lines in each file in the array arr:

for file in "${arr[@]}"; do
 wc -l "$file"
done
 
# 3 envvars
# 547 httpd.conf
# ...

Note that this pattern makes use of the @ symbol to retrieve all elements from the array.

More Bash Array Syntax

You can get the number of items in an array using the following:

echo ${#city[@]}
 
# 4

You can add a new element onto the end of a standard array like so:

arr+=(4)

So to add a fifth city to the list:

city+=(Rome)
echo ${city[@]}
 
# London Paris Milan New York Rome

To extract a chunk of an array, you can use a syntax that approximates the slice operation of many other languages:

${arr[@]:s:n}

This syntax will return a slice of the array beginning at position s and containing n items. You can omit the :n part to extract all items from s until the end of the list.

echo ${city[@]:2:2}
# Milan New York
 
echo ${city[@]:3}
# New York Rome

Bash Has Many Features, They Just Take Some Learning

Arrays in bash may have limitations, but they offer the same basic functionality as most programming languages do. Although bash has historically supported just straightforward one-dimensional arrays, times are changing. The latest version of bash, 4, supports associative arrays and negative array indexing.

Whichever version of bash you’re using, it’s important to understand its nuances. Even normal variable syntax has plenty of idiosyncrasies.

Source: BOBBY JACK
Via: makeuseof
Tags: How to Use Arrays in a Bash Script
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version