Fundamentals 4 min read

Master Linux Shell Arrays: Definition, Access, Modification, and Advanced Tricks

This tutorial explains how Linux shell arrays outperform Windows batch scripts, covering array definition, length retrieval, element access, assignment, deletion, slicing, and substitution with clear command examples and practical tips for effective scripting.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Linux Shell Arrays: Definition, Access, Modification, and Advanced Tricks

Linux shell scripting is far more powerful than Windows batch processing, especially for handling arrays.

1. Defining an array

a=(1 2 3 4 5)

Parentheses create an array; elements are separated by spaces.

2. Reading and assigning

Length

echo ${#a[@]} # => 5

Use ${#array[@]} or ${#array[*]} to obtain the array length.

Read element

echo ${a[2]} # => 3
echo ${a[*]} # => 1 2 3 4 5

Indexes start at 0; * or @ expands the entire array.

Assign

a[1]=100
echo ${a[*]} # => 1 100 3 4 5
a[5]=100
echo ${a[*]} # => 1 100 3 4 5 100

Assigning to a non‑existent index automatically appends a new element.

3. Deleting elements

unset a[1]
echo ${a[*]} # => 1 3 4 5

Use unset array[index] to remove a specific element; unset array clears the whole array.

4. Special operations

Slice

echo ${a[@]:0:3} # => 1 2 3
echo ${a[@]:1:4} # => 2 3 4 5

The syntax ${array[@]:start:length} returns a slice; wrapping the result in parentheses creates a new array.

Replace

echo ${a[@]/3/100} # => 1 2 100 4 5

The pattern ${array[@]/old/new} performs substitution without altering the original array; to persist the change, reassign the result to the array.

These commands demonstrate that Linux shell arrays are powerful and cover most common use cases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

command-lineArrays
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.