Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

UNIX Shell array


May 23, 2021 UNIX Getting started


Table of contents


Shell array

A shell variable can hold only one value. This type of variable is called a synth variable.

Shell array variables can hold multiple values at the same time, and it supports different types of variables. A rrays provide a way to group variable sets. Instead of creating a new name for each required variable, you can use an array variable to store all other variables.

All naming rules discussed in the shell variable will apply to named arrays.

Define array values

The difference between an array variable and a standard variable can be explained as follows.

If you want to depict the names of different students, you need to name a series of variable names as a collection of variables. Each individual variable is a standard variable, as follows:

    NAME01="Zara"
    NAME02="Qadir"
    NAME03="Mahnaz"
    NAME04="Ayan"
    NAME05="Daisy"

We can use an array to store all the names mentioned above. H ere is the easiest way to create an array variable and assign a value to an index of the array. This is represented as follows:

    array_name[index]=value

Here array_name is the name of the array, index is the index item in the array that needs to be assigned, and value is the value you want to set for that index item.

For example, the following command:

    NAME[0]="Zara"
    NAME[1]="Qadir"
    NAME[2]="Mahnaz"
    NAME[3]="Ayan"
    NAME[4]="Daisy"

If you use the ksh shell, the syntax for array initialization looks like this:

    set -A array_name value1 value2 ... valuen

If you use a bash shell, the syntax for array initialization looks like this:

    array_name=(value1 ... valuen)

Access array values

After assigning a value to an array variable, you can access it. Here's what it looks like:

    ${array_name[index]}

Here array_name is the name of the array, and index is the index of the value to be accessed. Here's the simplest example:

    #!/bin/sh

    NAME[0]="Zara"
    NAME[1]="Qadir"
    NAME[2]="Mahnaz"
    NAME[3]="Ayan"
    NAME[4]="Daisy"
    echo "First Index: ${NAME[0]}"
    echo "Second Index: ${NAME[1]}"

This results in the following:

    $./test.sh
    First Index: Zara
    Second Index: Qadir

You can access all the items in the array using one of the following methods:

    ${array_name[*]}
    ${array_name[@]}

The name array_name is the name of the array you are interested in. Here's the simplest example:

    #!/bin/sh

    NAME[0]="Zara"
    NAME[1]="Qadir"
    NAME[2]="Mahnaz"
    NAME[3]="Ayan"
    NAME[4]="Daisy"
    echo "First Method: ${NAME[*]}"
    echo "Second Method: ${NAME[@]}"

This results in the following:

    $./test.sh
    First Method: Zara Qadir Mahnaz Ayan Daisy
    Second Method: Zara Qadir Mahnaz Ayan Daisy