Skip to content

Use array in Bash

homepage-banner

Introduction

Bash is a powerful scripting language used on Unix-based systems. One of the key features of Bash is its ability to work with arrays. In this blog post, we’ll guide you through the basics of using arrays in Bash scripts.

Variables

$VAR
or
${VAR}

Arrays

To create an array, you can use the following syntax:

array_name=(value1 value2 value3 ...)
fruits=(apple banana orange)
${VAR[$i]}

Accessing Array Elements

To access an element in an array, you can use the following syntax:

${array_name[index]}

For example, to access the first element in the fruits array, you can use the following command:

echo ${fruits[0]}

This will output “apple”.

You can also access all the elements in an array using the following syntax:

${array_name[@]}

For example, to output all the fruits in the fruits array, you can use the following command:

echo ${fruits[@]}

This will output “apple banana orange”.

echo ${VAR[@]}

Count the number of elements in the array

echo ${#VAR[@]}

Read an array from a file

(Read by line)

VAR=(`cat 'eg.txt'`)

Looping Through an Array

To loop through all the elements in an array, you can use a for loop. The for loop in Bash can be used to iterate over a range of values or over an array. To loop through the fruits array, you can use the following code:

for fruit in "${fruits[@]}"
do
  echo $fruit
done

This will output all the elements of the fruits array to the console.

Modifying Array Elements

You can modify an element in an array by assigning a new value to it using the following syntax:

array_name[index]=new_value

For example, to change the value of the second element in the fruits array to “kiwi”, you can use the following command:

fruits[1]=kiwi

You can also add new elements to an array using the following syntax:

array_name+=(new_value)

For example, to add “pear” to the fruits array, you can use the following command:

fruits+=(pear)

Conclusion

In this blog post, we’ve covered the basics of working with arrays in Bash. Arrays are a powerful feature of Bash that can be used to store and manipulate data in your scripts. With this knowledge, you can now start using arrays in your Bash scripts to simplify your code and make it more efficient.

Leave a message