温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.muo.com/bash-script-array-usage/
点击访问原文链接

How to Use Arrays in a Bash Script

How to Use Arrays in a Bash Script Menu Sign in now Close PC & Mobile Submenu Windows2 Linux Android Apple Technical Submenu Tech Explained Security Software Submenu Productivity Internet Creative Screen Submenu Entertainment Streaming Home Submenu Smart Home Home News Sign in Newsletter Menu Follow Followed Like More Action Sign in now Productivity Android Smart TVs Networking Windows 11 Entertainment Close
How to Use Arrays in a Bash Script no attribution required (image from Pixabay) https://pixabay.com/photos/programming-developing-startup-593312/ By  Bobby Jack Published Apr 11, 2022, 6:00 AM EDT A technology enthusiast, Bobby studied Computer Science at the University of Southampton before working in a number of roles across industries, from the private sector to the charitable one, at multinationals and startups. He’s helped maintain backend Java servers, designed databases and front-end interfaces, and created a bespoke content management system.

Bobby also enjoys video gaming, and has written for several outlets, including a stint as Editor-in-Chief at Switch Player Magazine and contributions to online magazine, SUPERJUMP. Bobby uses a Mac for day-to-day work and an Android phone for distractions. Sign in to your MakeUseOf account

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.

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.

Close
Recommended Bash Variables Explained: A Simple Guide With Examples This is the only version of Windows 11 I install on new PCs now I edit photos in my browser now, and Photoshop feels pointless I stopped Windows from keeping old drivers and my PC boot time dropped by half Join Our Team Our Audience About Us Press & Events Media Coverage Contact Us Follow Us Advertising Careers Terms Privacy Policies MakeUseOf is part of the Valnet Publishing Group Copyright © 2026 Valnet Inc.

How to Use Arrays in a Bash Script,AI智能索引,全网链接索引,智能导航,网页索引

    Arrays can simplify many tasks, especially when you need to repeat an action across several files. Find out how to use them in your bash scripts.