Next: The Directory Stack , Previous: Aliases , Up: Bash Features   [ Contents ][ Index ]

Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Indexed arrays are referenced using integers (including arithmetic expressions (see Shell Arithmetic )) and are zero-based; associative arrays use arbitrary strings. Unless otherwise noted, indexed array indices must be non-negative integers.

An indexed array is created automatically if any variable is assigned to using the syntax

The subscript is treated as an arithmetic expression that must evaluate to a number. To explicitly declare an array, use

is also accepted; the subscript is ignored.

Associative arrays are created using

Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.

Arrays are assigned to using compound assignments of the form

where each value may be of the form [ subscript ]= string . Indexed array assignments do not require anything but string . When assigning to indexed arrays, if the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero.

Each value in the list undergoes all the shell expansions described above (see Shell Expansions ).

When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name =( key1 value1 key2 value2 … ). These are treated identically to name =( [ key1 ]= value1 [ key2 ]= value2 … ). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string.

This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name [ subscript ]= value syntax introduced above.

When assigning to an indexed array, if name is subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of name , so negative indices count back from the end of the array, and an index of -1 references the last element.

The ‘ += ’ operator will append to an array variable when assigning using the compound assignment syntax; see Shell Parameters above.

Any element of an array may be referenced using ${ name [ subscript ]} . The braces are required to avoid conflicts with the shell’s filename expansion operators. If the subscript is ‘ @ ’ or ‘ * ’, the word expands to all members of the array name . These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${ name [*]} expands to a single word with the value of each array member separated by the first character of the IFS variable, and ${ name [@]} expands each element of name to a separate word. When there are no array members, ${ name [@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters ‘ @ ’ and ‘ * ’. ${# name [ subscript ]} expands to the length of ${ name [ subscript ]} . If subscript is ‘ @ ’ or ‘ * ’, the expansion is the number of elements in the array. If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpreted as relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and an index of -1 refers to the last element.

Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0. Any reference to a variable using a valid subscript is legal, and bash will create an array if necessary.

An array variable is considered set if a subscript has been assigned a value. The null string is a valid value.

It is possible to obtain the keys (indices) of an array as well as the values. ${! name [@]} and ${! name [*]} expand to the indices assigned in array variable name . The treatment when in double quotes is similar to the expansion of the special parameters ‘ @ ’ and ‘ * ’ within double quotes.

The unset builtin is used to destroy arrays. unset name [ subscript ] destroys the array element at index subscript . Negative subscripts to indexed arrays are interpreted as described above. Unsetting the last element of an array variable does not unset the variable. unset name , where name is an array, removes the entire array. unset name [ subscript ] behaves differently depending on the array type when given a subscript of ‘ * ’ or ‘ @ ’. When name is an associative array, it removes the element with key ‘ * ’ or ‘ @ ’. If name is an indexed array, unset removes all of the elements, but does not remove the array itself.

When using a variable name with a subscript as an argument to a command, such as with unset , without using the word expansion syntax described above, the argument is subject to the shell’s filename expansion. If filename expansion is not desired, the argument should be quoted.

The declare , local , and readonly builtins each accept a -a option to specify an indexed array and a -A option to specify an associative array. If both options are supplied, -A takes precedence. The read builtin accepts a -a option to assign a list of words read from the standard input to an array, and can read values from the standard input into individual array elements. The set and declare builtins display array values in a way that allows them to be reused as input.

Learn to Code. Shape Your Future

Bash Array

Bash Array Explained: A Complete Guide

The Bash array data type gives you a lot of flexibility in the creation of your shell scripts.

Bash provides two types of arrays: indexed arrays and associative arrays. Indexed arrays are standard arrays in which every element is identified by a numeric index. In associative arrays every element is a key-value pair (similarly to dictionaries in other programming languages).

In this tutorial we will start by getting familiar with indexed arrays, then we will also see how associative arrays differ from them (they also have few things in common).

By the end of this tutorial you will clarify any doubts you might have right now about arrays in Bash.

And you will also learn lots of cool things you can do in your shell scripts with arrays.

Letā€™s get started!

Table of Contents

Bash Indexed Array of Strings

We will start by creating an indexed array of strings where the strings are directory names in a Linux system :

First of all letā€™s see what gets printed when we echo the value of the array variable dirs:

When you print a Bash array variable the result is the first element of the array.

Another way to print the first element of the array is by accessing the array based on its index.

Bash indexed arrays are zero based, this means that to access the first element we have to use the index zero.

Wonder why we are using curly brackets ?

We can understand why by removing them to see what the ouput is:

Bash prints the first element of the array followed by [0] because it only recognises $dirs as a variable. To include [0] as part of the variable name we have to use curly brackets .

In the same way, to print the second element of the array we will access the index 1 of the array:

What if we want to access the last element of the array?

Before doing that we have to find out how to get the length of a Bash arrayā€¦

How Do You Determine the Length of a Bash Array?

To find the length of an array in Bash we have to use the syntax ${#array_name[@]}.

Letā€™s apply it to our example:

The syntax might seem hard to remember when you see it for the first timeā€¦

ā€¦but donā€™t worry, just practice it a few times and you will remember it.

Access the Last Element of a Bash Array

Now that we know how to get the number of elements in a Bash array, we can use this information to retrieve the value of the last element.

First we have to calculate the index of the last element that is equal to the number of elements in the array minus one (remember that Bash arrays are zero-based as usually happens in most programming languages).

This value will be the index to pass when we want to print the last element of the array:

Definitely not one of the easiest ways to retrieve the last element of an array, if you are familiar with other programming languages šŸ˜€

Since Bash 4.2 arrays also accept negative indexes that allow to access elements starting from the end of the array.

To verify your version of Bash use the following command:

To access the last element of a Bash indexed array you can use the index -1 (for Bash 4.2 or later). Otherwise use the following expression ${array_name[${#array_name[@]}-1]}.

As expected we get back the last element.

How to Print All the Values in a Bash Array

To print all the elements of an array we still need to use the square brackets and replace the index with the @ symbol:

An alternative to the @ is the * sign:

Why two ways to do the same thing?

Whatā€™s the difference between * and @ when used to print all the elements of a Bash array?

We will see it later, after showing you how to use a for loop to go through all the elements of an arrayā€¦

How to Update a Bash Array Element

Now, how can we update an element in our array?

We will use the following syntax:

In our case I want to set the value of the second element (index equal to 1) to ā€œ/usrā€.

Loop Through Bash Array Elements

Letā€™s find out how to create a for loop that goes through all the elements of an array:

The output is:

Going back to the difference between * and @, what happens if we replace ${dirs[@]} with ${dirs[*]} ?

No differenceā€¦

The difference becomes evident when we surround the two expressions with double quotes.

You can see that when we use the * our array is interpreted as a single value.

For Loop Using the Indexes of a Bash Array

Letā€™s try something elseā€¦

We will use the following expression:

Notice that we have added an exclamation mark before the name of the array.

Letā€™s see what happens when we do that.

This time instead of printing all the elements of the array we have printed all the indexes.

The expression ${!array_name[@]} is used to print all the indexes of a Bash array.

As you can imagine we can use this to create a for loop that instead of going through all the elements of the array goes through all the indexes of the array. From 0 to the length of the array minus 1:

Verify that the output is identical to the one we have seen by going through all the elements in the array instead of all the indexes.

We can also print the index for each element if we need it:

Using Declare For Indexed Arrays

We have created our indexed array in the following way:

Below you can see other two ways to create indexed arrays:

Define an empty array and set its elements one by one:

Using the Bash declare builtin with the -a flag:

Append Elements to a Bash Indexed Array

To append an element to an existing array we can use the following syntax:

For example:

What about appending more than one element?

Hereā€™s how you can do itā€¦

Makes sense?

How to Remove an Element From an Array

To remove an element from an array you can use unset :

Notice how the third element of the array (identified by the index 2) has been removed from the array.

You can also use unset to delete the entire array :

Confirm that the last echo command doesnā€™t return any output.

Summary of Bash Array Operations

Before moving to associative arrays I want to give you a summary of the Bash array operations we have covered.

Practice all the commands in this table before continuing with this tutorial.

Many of the operations in the table also apply to associative arrays.

Initialize a Bash Associative Array

Associative arrays can be only defined using the declare command.

As we have seen before, to create an indexed array you can also use the following syntax:

To create an associative array change the flag passed to the declare command, use the -A flag :

Notice how the order of the elements is not respected with Bash associative arrays as opposed as with indexed arrays.

When you have an array with lots of elements it can also help writing the commands that assign key/value pairs to the array in the following way:

How to Use a For Loop with a Bash Associative Array

The syntax of the for loops for associative arrays is pretty much identical to what we have seen with indexed arrays.

We will use the exclamation mark to get the keys of the array and then print each value mapped to a key:

Can you see how every key is used to retrieve the associated value?

Delete an Element From an Associative Array

Letā€™s see how you can delete an element from an associative arrayā€¦

The following command removes the element identified by the key key1 from the associative array we have defined previously.

Confirm that you get the following output when you execute the for loop we have seen in the previous section:

To delete the full array you can use the same syntax we have seen with indexed arrays:

The next few sections will show you some useful operations you can perform with Bash arrays as part of your day-to-day scriptingā€¦

Remove Duplicates From an Array

Have you ever wondered how to remove duplicates from an array?

To do that we could use a for loop that builds a new array that only contains unique values.

But instead, I want to find a more concise solution.

We will use four Linux commands following the steps below:

  • Print all the elements of the array using echo .
  • Use tr to replace spaces with newlines. This prints all the element on individual lines.
  • Send the output of the previous step to the sort and uniq commands using pipes.
  • Build a new array from the output of the command created so far using command substitution.

This is the original array and the output described up to step 3:

Now, letā€™s use command substitution, as explained in step 4, to assign this output to a new array. We will call the new array unique_numbers:

The following for loops prints all the elements of the new array:

The output is correct!

I wonder if it also works for an array of stringsā€¦

Notice how we have written the Bash for loop in a single line.

Here is the output. It works for an array of strings tooā€¦

With this example we have also seen how to sort an array.

Check If a Bash Array Contains a String

To verify if an array contains a specific string we can use echo and tr in the same way we have done in the previous section.

Then we send the output to the grep command to confirm if any of the elements in the array matches the string we are looking for.

Here is how it works if, for example, we look for the string ā€œcommandā€:

We can use the -q flag for grep to avoid printing any output. The only thing we need is the exit code of the command stored in the $? variable .

We can then use an if else statement to verify the value of $?

This is how we verify if the array has an element equal to ā€œcommandā€.

In the same way we can find if a Bash associative array has a key.

We would simply replace ${words[@]} with ${!words[@]} to print all the keys instead of the values.

Give it a try!

Bash Array of Files in a Directory

I want to show you another example on how to generate an array from a command output.

This is something you will definitely find useful when creating your scripts.

We will create an array from the output of the ls command executed in the current directory:

Once again, notice how we use command substitution to assign the output of the command to the elements of the array.

How to Reverse an Array in Bash

We can use a very similar command to the one used to remove duplicates from an array also to reverse an array.

The only difference is that we would also use the Linux tac command (opposite as cat) to reverse the lines we obtain from the elements of the array:

How to Copy a Bash Indexed Array

Here is how you can copy an indexed array in Bash.

Given the following array:

I can create a copy using the following command:

With a for loop we can confirm the elements inside the copy of the array:

Slicing a Bash Array

Sometimes you might want to just get a slice of an array.

A slice is basically a certain number of elements starting at a specific index.

This is the generic syntax you would use:

Letā€™s test this expression on the following array:

Two elements starting from index 1

One element starting from index 0

Three elements starting from index 0

To get all the elements of an array starting from a specific index (in this case index 1) you can use the following:

Search And Replace An Array Element

At some point you might need to search a replace an element with a specific valueā€¦

ā€¦hereā€™s how you can do it:

In our array I want to replace the word bash with the word linux:

Quite handy!

I wonder if it works if there are multiple occurrences of the element we want to replaceā€¦

How to Concatenate Two Bash Arrays

I want to concatenate the following two arrays:

I can create a new array as a result of a merge of the two arrays:

Letā€™s confirm the values and the number of elements in this array:

Verify If Bash Array Is Empty

Why would you check if a Bash array is empty?

There are multiple scenarios in which this could be useful, one example is if you use an array to store all the errors detected in your script.

At the end of your script you check the number of elements in this array and print an error message or not depending on that.

We will use an array called errors and a Bash if else statement that checks the number of elements in the array.

In this example I will create the errors array with one element:

When I run the script I get the following output:

A nice way to track errors in your scripts!

Create a Bash Array From a Range of Numbers

How can I create an array whose elements are numbers between 1 and 100?

We will do it in the following way:

  • Create an empty array.
  • Use a for loop to append the numbers between 1 and 100 to the array.

Give it a try and confirm that the numbers between 1 and 100 are printed by the script.

We can also verify the number of elements in the array:

How To Implement a Push Pop Logic for Arrays

Given an indexed array of strings:

I want to implement a push pop logicā€¦

ā€¦where push adds an element to the end of the array and pop removes the last element from the array.

Letā€™s start with push, we will just have to append an element the way we have seen before:

The pop logic gets the value of the last element and then removes it from the array:

You can also wrap those commands in two Bash functions so you can simply call push() and pop() instead of having to duplicate the code above every time you need it.

Bad Array Subscript Error

At some point while I was working on this tutorial I encountered the following error:

I was executing the following script:

Apparently there wasnā€™t anything wrong in line 4 of the script.

As we have seen in one of the previous sections, the index -1 can be used to access the last element of an array.

After a bit of troubleshooting I realised that the problem was caused byā€¦

ā€¦the version of Bash running on my machine!

In version 3 Bash didnā€™t support negative indexes for arrays and, as explained in the section of this article ā€œAccess the Last Element of a Bash Arrayā€ , alternative solutions are possible.

Another option is upgrading your version of Bash as long as itā€™s supported by your operating system.

Letā€™s see another scenario in which this error can occurā€¦

Hereā€™s another script:

As you can see Iā€™m using the declare builtin to create an associative array (Iā€™m using the -A flag as learned in one of the sections above).

When I run the script I see the following error:

This time, as you can see from the message, the error is caused by the fact that Iā€™m trying to add an element with an empty key to the array.

This is another reason why this error can occur.

So, now you know two different causes of the ā€œbad array subscriptā€ error and if you see it in your scripts you have a way to understand it.

We have covered so much in this blog post!

You should be a lot more comfortable with Bash arrays now compared to when you started reading this article.

Letā€™s do a quick recap of the topics we covered, you might spot something you want to go back and review.

We have seen how to:

  • Define indexed and associative arrays.
  • Determine the length of an array.
  • Access elements based on indexes (for indexed arrays) and keys (for associative arrays).
  • Print all the elements using either @ or *.
  • Update array elements.
  • Loop through a Bash array using either the elements or the indexes.
  • Create indexed and associative arrays using the declare builtin .
  • Append elements to an existing array.
  • Remove elements from an array or delete the entire array.
  • Remove duplicates from an array.
  • Check if an array contains an element that matches a specific string.
  • Reverse , copy and get a slice of an array.
  • Search and replace a string in arrays.
  • Concatenate two arrays and verify if an array is empty .
  • Create an array from a range of numbers.
  • Implement a push / pop logic for Bash arrays.
  • Understand the ā€œbad array subscriptā€ error.

Now itā€™s your time to use Bash arraysā€¦.

ā€¦but before finishing I have a question for you to test your knowledge.

  • What type of array is this one? Indexed or associative?
  • How can you print the keys of this array?

Let me know in the comments.

Happy scripting! šŸ™‚

Claudio Sabato - Codefather - Software Engineer and Programming Coach

Claudio Sabato is an IT expert with over 15 years of professional experience in Python programming, Linux Systems Administration, Bash programming, and IT Systems Design. He isĀ a professional certified by the Linux Professional Institute .

With a Masterā€™s degree in Computer Science, he has a strong foundation in Software Engineering and a passion for robotics with Raspberry Pi.

Related posts:

  • Loop Through the Lines of a File: Bash For Loop Explained
  • Exit a Bash Script: Exit 0 and Exit 1 Explained
  • Bash While Loop: An Easy Way to Print Numbers from 1 to N
  • Bash Syntax Error Near Unexpected Token: How to Fix It

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

CODEFATHER

  • Privacy Overview
  • Strictly Necessary Cookies

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

A Complete Guide on How To Use Bash Arrays

The Bash array variables come in two flavors, the one-dimensional indexed arrays , and the associative arrays . The indexed arrays are sometimes called lists and the associative arrays are sometimes called dictionaries or hash tables . The support for Bash Arrays simplifies heavily how you can write your shell scripts to support more complex logic or to safely preserve field separation.

This guide covers the standard bash array operations and how to declare ( set ), append , iterate over ( loop ), check ( test ), access ( get ), and delete ( unset ) a value in an indexed bash array and an associative bash array . The detailed examples include how to sort and shuffle arrays.

šŸ‘‰ Many fixes and improvements have been made with Bash version 5, read more details with the post What’s New in GNU Bash 5?

Difference between Bash Indexed Arrays and Associative Arrays

How to declare a bash array.

Arrays in Bash are one-dimensional array variables. The declare shell builtin is used to declare array variables and give them attributes using the -a and -A options. Note that there is no upper limit (maximum) on the size (length) of a Bash array and the values in an Indexed Array and an Associative Array can be any strings or numbers, with the null string being a valid value.

šŸ‘‰ Remember that the null string is a zero-length string, which is an empty string. This is not to be confused with the bash null command which has a completely different meaning and purpose.

Bash Indexed Array (ordered lists)

You can create an Indexed Array on the fly in Bash using compound assignment or by using the builtin command declare . The += operator allows you to append a value to an indexed Bash array.

With the declare built-in command and the lowercase “ -a ” option, you would simply do the following:

Bash Associative Array (dictionaries, hash table, or key/value pair)

You cannot create an associative array on the fly in Bash. You can only use the declare built-in command with the uppercase “ -A ” option. The += operator allows you to append one or multiple key/value to an associative Bash array.

āš ļø Do not confuse -a (lowercase) with -A (uppercase). It would silently fail. Indeed, declaring an Indexed array will accept subscript but will ignore it and treat the rest of your declaration as an Indexed Array, not an Associative Array.
šŸ‘‰ Make sure to properly follow the array syntax and enclose the subscript in square brackets [] to avoid the " Bash Error: must use subscript when assigning associative array " .

When to use double quotes with Bash Arrays?

A great benefit of using Bash Arrays is to preserve field separation. Though, to keep that behavior, you must use double quotes as necessary. In absence of quoting, Bash will split the input into a list of words based on the $IFS value which by default contain spaces and tabs.

Array Operations

How to iterate over a bash array (loop).

As discussed above, you can access all the values of a Bash array using the * (asterisk) notation. Though, to iterate through all the array values you should use the @ (at) notation instead.

How to get the Key/Value pair of a Bash Array? (Obtain Keys or Indices)

When looping over a Bash array it’s often useful to access the keys of the array separately of the values. This can be done by using the ! (bang) notation.

How to get a Bash Array size? (Array length)

Another useful aspect of manipulating Bash Arrays is to be able to get the total count of all the elements in an array. You can get the length (i.e. size) of an Array variable with the # (hashtag) notation.

How to remove a key from a Bash Array or delete the full array? (delete)

The unset bash builtin command is used to unset (delete or remove) any values and attributes from a shell variable or function. This means that you can simply use it to delete a Bash array in full or only remove part of it by specifying the key. unset take the variable name as an argument, so don’t forget to remove the $ (dollar) sign in front of the variable name of your array. See the complete example below.

Detailed Examples & FAQ

How to shuffle the elements of an array in a shell script.

There are two reasonable options to shuffle the elements of a bash array in a shell script. First, you can either use the external command-line tool shuf that comes with the GNU coreutils, or sort -R in older coreutils versions. Second, you can use a native bash implementation with only shell builtin and a randomization function. Both methods presented below assume the use of an indexed array, it will not work with associative arrays.

The shuf command line generates random permutations from a file or the standard input. By using the -e option, shuf would treat each argument as a separate input line. Do not forget to use the double-quote otherwise elements with whitespaces will be split . Once the array is shuffled we can reassign its new value to the same variable.

How to sort the elements of an Array in a shell script?

How to get a subset of an array.

The shell parameter expansions works on arrays which means that you can use the substring Expansion ${string:<start>:<count>} notation to get a subset of an array in bash. Example: ${myArray[@]:2:3} .

The notation can be use with optional <start> and <count> parameters. The ${myArray[@]} notation is equivalent to ${myArray[@]:0} .

How to check if a Bash Array is empty?

How to check if a bash array contains a value.

In order to look for an exact match, your regex pattern needs to add extra space before and after the value like (^|[[:space:]])"VALUE"($|[[:space:]]) .

With the Bash Associative Arrays, you can extend the solution to test values with [[ -z "${myArray[$value]}" ]] .

How to store each line of a file into an indexed array?

The easiest and safest way to read a file into a bash array is to use the mapfile builtin which read lines from the standard input. When no array variable name is provided to the mapfile command, the input will be stored into the $MAPFILE variable. Note that the mapfile command will split by default on newlines character but will preserve it in the array values, you can remove the trailing delimiter using the -t option and change the delimiter using the -d option.

Bash Arrays Explained: A Simple Guide With Examples

Get to grips with Bash arraysā€”how to declare them, manipulate them, and delete them.

Arrays are data stores used to hold values that have some relation to one another. Unlike in most programming languages, Bash arrays can store values of different data types in the same array.

Bash has two types of arrays: indexed arrays and associative arrays. For indexed arrays, the indexes begin from 0 to (n-1), as is common in most languages. However, arrays in Bash are sparse. This means that you can assign the (n-1)th array element without having assigned the (n-2)th element.

In this tutorial, you will learn how to work with arrays in Bash. Let's get started.

Defining Arrays

There are three ways you can define arrays in Bash. Similar to Bash variables, arrays need to be initialized at creation. The only exception to this is if you're using the declare keyword. You also need to be sure that no space is left on either side of the assignment operator as you're initializing the array.

The first method is compound assignment of values to the array name. There are two ways to do this:

In the first compound assignment, the values in the round brackets are assigned sequentially from the index [0] to [3] .

However, in the second, the values are assigned to an index in whichever order the programmer has indicated.

Related: What Are Environment Variables in Linux? Everything You Need to Know

If you took close notice to arr2 , you'll notice that index [2] was left out. The array will still be created without any errors thrown. This assignment is actually a demonstration of sparse storage in Bash arrays as we touched on earlier.

Notice that there are no commas separating the array values. The values are simply separated by spaces.

The second method indirectly declares the array. You can just start assigning values to null array elements:

The third way is to explicitly declare the array with the keyword declare :

Operations on Arrays

To access array elements, use this syntax: ${array[index]}

If you need to print out the entire array instead, use the @ symbol as the

index of ${array[index]} :

To find out the number of elements in the array, use the # symbol as shown below:

You may also need to modify array elements—see the example below on how to do so. It's similar to how you add a new element. The only difference is that you're replacing a value to an index that already has a value.

Associative Arrays

An array that has arbitrary values as its keys is called an associative array. These arrays are used to store related key-value pairs.

Related: How to Turn Bash Scripts Into Clickable Apps Using AppleScript

To define an associative array, you need to do so explicitly using the keyword declare .

You can access a member element in the same way you do indexed arrays:

If you wish to print out all the values, you can use the @ symbol as shown below:

If you want to print out all the array keys, you can use the @ and ! symbols as demonstrated below:

To find the number of elements the associative array has, use the same syntax you'd use with indexed arrays (demonstrated in the last section).

If you wish to delete an array item or the entire array, use the syntax below:

Using the printf Command

You may have noticed that this whole article uses the echo command to output data to the shell. The echo command works for this tutorial but has few features and flexibility when it comes to string formatting.

However, the printf command offers more specific formatting options that make Bash scripting a breeze. Learning the printf function will surely enhance your string formatting experience and efficiency in Bash.

  • The Ultimate Bash Array Tutorial with 15 Examples

An array is a variable containing multiple values may be of same type or of different type.Ā  There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Array index starts with zero.

In this article, let us review 15 various array operations in bash. This article is part of the on-going Bash Tutorial series. For those who are new to bash scripting, get a jump-start from the Bash Scripting Introduction tutorial .

1. Declaring an Array and Assigning values

In bash, array is created automatically when a variable is used in the format like,

  • name is any name for an array
  • index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.

To access an element from an array use curly brackets like ${name[index]}.

2. Initializing an array during declaration

Instead of initializing an each element of an array separately, you can declare and initialize an array by specifying the list of elements (separated by white space) with in a curly braces.

If the elements has the white space character, enclose it with in a quotes.

declare -a declares an array and all the elements in the parentheses are the elements of an array.

3. Print the Whole Bash Array

There are different ways to print the whole elements of the array. If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash.

Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero.

4. Length of the Bash Array

We can get the length of an array using the special parameter called $#.

${#arrayname[@]} gives you the length of the array.

5. Length of the nth Element in an Array

${#arrayname[n]} should give the length of the nth element in an array.

6. Extraction by offset and length for an array

The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.

The above example returns the elements in the 3rd index and fourth index. Index always starts with zero.

7. Extraction with offset and length, for a particular element of an array

To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array.

The above example extracts the first four characters from the 2nd indexed element of an array.

8. Search and Replace in an array elements

The following example, searches for Ubuntu in an array elements, and replace the same with the word ‘SCO Unix’.

In this example, it replaces the element in the 2nd index ‘Ubuntu’ with ‘SCO Unix’. But this example will not permanently replace the array content.

9. Add an element to an existing Bash Array

The following example shows the way to add an element to the existing array.

In the array called Unix, the elements ‘AIX’ and ‘HP-UX’ are added in 7th and 8th index respectively.

10. Remove an Element from an Array

unset is used to remove an element from an array.unset will have the same effect as assigning null to an element.

The above script will just print null which is the value available in the 3rd index. The following example shows one of the way to remove an element completely from an array.

In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index. And merge both the above output. This is one of the workaround to remove an element from an array.

11. Remove Bash Array Elements using Patterns

In the search condition you can give the patterns, and stores the remaining element to an another array as shown below.

The above example removes the elements which has the patter Red*.

12. Copying an Array

Expand the array elements and store that into a new array as shown below.

13. Concatenation of two Bash Arrays

Expand the elements of the two arrays and assign it to the new array.

It prints the array which has the elements of the both the array ‘Unix’ and ‘Shell’, and number of elements of the new array is 14.

14. Deleting an Entire Array

unset is used to delete an entire array.

After unset an array, its length would be zero as shown above.

15. Load Content of a File into an Array

You can load the content of the file line by line into an array.

In the above example, each index of an array element has printed through for loop.

Recommended Reading

bash array element assignment

If you enjoyed this article, you might also like..

Tagged as: Bash Array String , Bash Arrays , Bash Script Array , Bash Scripting Tutorial , Bash Tutorial , Echo Array , Linux Array , Unix Array

Comments on this entry are closed.

Good article.

I am new to linux and following your articles very closely. Just wanted to confirm if the below line as typo in displaying code or the sentence it self “declare -a declares an array and all the elements in the curly brackets are the elements of an array” – are we using curly brackets or parantheses?

Thanks, Tanmay

Great stuff!!! Regards

Great examples šŸ™‚

There is a correction for number 6 though as the OpenLinux array entity is missing the closing single quote which would as you know, throw an error.

Keep up the good work

@Tanmay, @Bryan,

Thanks for pointing out the issues. They are fixed now.

1. “echo ${Unix[1]}” will not necessarily print element 1 from the array. For example:

$ Unix[1]=” AAA BBB CCC” $ echo ${Unix[1]} AAA BBB CCC

Leading and trailing whitespace will be lost, and consecutive whitespace will be reduced to a single space.

It should be:

echo “${Unix[1]}”

(Almost all the examples exhibit the same error because the variable reference is not quoted. Whether the error is manifest in the output depends on the contents of the array elements.)

2. “declare -a” is unnecessary

3. “echo ${Unix[@]}” has the same problem as #1

4. More accurately, ${#arrayname[@]} gives you the number of elements in the array.

9. Since bash3, elements can also be appended to an array with “+=”:

Unix+=( “AIX” “HP-UX” )

15. filecontent=( `cat “logfile” `)

More efficient, as it doesn’t require an external command, is:

filecontent=( `< "logfile" `)

(Note: this doesn't read the file line by line; it reads it word by word. Try it on a file with more than one word on a line.)

Since bash4, this can be done even more efficiently with the mapfile builtin:

mapfile -t filecontent < "$logfile"

for t in "${filecontent[@]}"

The loop is not necessary:

printf "%s\n" "${filecontent[@]}"

Note that the example will not read the following file into an array (where each line is an element). This is the first line This is the second line This is the final line To read the file (as lines) into an array do: { IFS=$’\n’ array_name=( $(cat filename) ) } Note the use of the “{” in this example allows the changing of IFS value without having to save it and restore it.

I love it! Great examples to display simple use cases.

Sadly, the syntax for arrays in Bash is too complex for me, so I’ll be staying with Perl. How often do you hear that? šŸ˜‰ I’ll probably be back here when perl isn’t allowed on a system for some reason.

Simply awsome! Thank you!

When you do:

filecontent=( `cat ā€œlogfileā€ `)

and logfile have one “*” you get a list of archives in your directory, how i can solve it?

WaS, when you do that, $logfile will contain just an asterisk (*).

If you want to display that asterisk, you must quote the variable reference or the wildcard will be expanded:

printf “%s\n” “$logfile”

echo “$logfile”

(Always quote variable references unless you have a good reason not to.)

To read a file into an array it’s possible to use the readarray or mapfile bash built-ins. readarray < filename or mapfile < filename

File is read into MAPFILE variable by default.

Thanks a lot! Great tutorial! It was very useful! Congrats!

Good Examples. Thank you for hard work and clear explanations. Error in number 12: Suse is omitted from the copied array.

I need to use cntrC inside my shell script. Here is an example: ” run some commands cntLc run some more commands

How can I have my shell script generate cntrC without me typing cnrlC?

Vivek, what do you really want to do?

Chris, I need to run a script which has a command which gives a running output. I need to change the argument to that command for example from 1 to 10. Example: for a in $(seq 1 10) do

Now gives a running output. Now when a=1, the command is running. I want to send cntrlC to the command so that ends after lets say 100 seconds and starts.

Vivek, what does this have to do with arrays?

for n in {1..10} do : whatever done &

read && kill “$!”

More accurately, the length of the Nth element in an array will give the statement with the N-1 index, i.e. ${#arrayname[N-1]}.

Thanks for the tutorial! It’s really great!

white space in elements not getting eliminated even though quotes are used

How about “test to see if value is in array” example?

Below is a small function for achieving this. The search string is the first argument and the rest are the array elements:

containsElement () { local e for e in “${@:2}”; do [[ “$e” == “$1” ]] && return 0; done return 1 } A test run of that function could look like:

$ array=(“something to search for” “a string” “test2000”) $ containsElement “a string” “${array[@]}” $ echo $? 0 $ containsElement “blaha” “${array[@]}” $ echo $? 1

Josh, there’s no need for a loop:

arraycontains() #@ USAGE: arraycontains STRING ARRAYNAME [IFS] { local string=$1 array=$2 localarray IFS=${3:-:} eval “localarray=( \”\${$array[@]}\” )” case “$IFS${localarray[*]}$IFS” in *”$IFS$string$IFS”*) return ;; *) return 1 ;; esac }

I have posted a number of functions for manipulating arrays at http://cfajohnson.com/shell/arrays/

As a historical note: SuSE has a lower-case “u” and the rest upper-case because it originally stood for “Software und System-Entwicklung”, meaning “Software and systems development”. (Ref: http://en.wikipedia.org/wiki/SuSE )

I’m a fan of clear code that is easy to read, but was curious whether Mr. Johnson’s arraycontains method had an efficiency benefit (in spite of its more obfuscated nature) over Josh’s (which is almost exactly the method I had been using). I can’t get it to work at all. Maybe I’m missing something, but in case I’m not, maybe I can save someone else the wasted effort in going down this same road.

Here is my test of Chris Johnson’s code:

#!/bin/bash arraycontains() { #@ USAGE: arraycontains STRING ARRAYNAME [IFS] local string=$1 array=$2 localarray IFS=${3:-:} eval “localarray=( \”\${$array[@]}\” )” case “$IFS${localarray[*]}$IFS” in *”$IFS$string$IFS”*) return ;; *) return 1 ;; esac }

echo -en “String test 1: ” one=(“and” “this” “is” “another” “test”) if arraycontains “something” “${one[@]}” then echo “TRUE, but should be FALSE” else echo “OK” fi

echo -en “String test 2: ” if arraycontains “another” “${one[@]}” then echo “OK” else echo “FALSE, but should be TRUE” fi

echo -en “Numeric test: ” two=(1 2 3 4 5) arraycontains “5” “${two[@]}” echo $?

echo -en “Quoted-numeric test: ” three=(“1” “2” “3” “4” “5”) arraycontains “6” “${three[@]}” echo $?

Here is the output:

$ sh test-contains.sh String test 1: OK String test 2: FALSE, but should be TRUE Numeric test: ./test-contains.sh: line 4: ${1[@]}: bad substitution 1 Quoted-numeric test: ./test-contains.sh: line 4: ${1[@]}: bad substitution 1

Besides giving the error message when passed a numeric array, it always returns FALSE (1). On investigation I discovered that the “eval” line is not working; localarray is always blank (so no wonder it always returns false).

I ran this script with BASH 3.00.16 and 4.2.20 and got the same result.

yeah… am well and much clear on array in linux command.. wel done stay blessed,

The second part of Example 10 is especially wrong because of the quoting issue. It means ${Unix[1]} is Red instead of Red hat. The correct way is

Unix=(“${Unix[@]:0:$pos}” “${Unix[@]:$(($pos + 1))}”)

The best guide on Bash arrays I have ever found!

To read the file as lines into an array use double quote

fileContents=( “$(cat sunflower.html)” )

for line in “${fileContents[@]}” do echo “$line” done

mug896, That will not read the file line by line; it will read it word by word. All whitespace in the file will act as delimiters.

And you don’t need a loop to print out the array:

printf ‘%s\n’ “${fileContents[@]}”

My mistake, mug896; your code will read the file into a single element of the array. You can see that by:

printf ‘%s\n’ ā€œ${fileContents[0]}ā€

If you had done

fileContents=( $(cat sunflower.html) ) ## no quotes

It would have read each word into a separate element of the array.

Very nice, but “iteration on an array” is missing !

Thanks a lot!

What do you do when a bash script doesn’t accept arrays?

Error messages: >>>> “declare: not found” or >>>> “Unix[0]=Debian: not found”

Robert, make sure you are using bash to interpret the script.

Your second example in “10. Remove an Element from an Array” is wrong because you are not enclosing the array parts in quotes – so ‘Red Hat’ becomes two elements.

Here it is fixed up with proofs.

Fri Feb 28 – 12:53 PM > Unix=(‘Debian’ ‘Red hat’ ‘Ubuntu’ ‘Suse’ ‘Fedora’ ‘UTS’ ‘OpenLinux’); Fri Feb 28 – 12:53 PM > echo ${#Unix[@]} 7 Fri Feb 28 – 12:53 PM > pos=3 Fri Feb 28 – 12:53 PM > echo ${Unix[$pos]} Suse Fri Feb 28 – 12:53 PM > Unix=(“${Unix[@]:0:$pos}” “${Unix[@]:$(($pos + 1))}”) Fri Feb 28 – 12:53 PM > echo ${Unix[$pos]} Fedora Fri Feb 28 – 12:53 PM > echo ${Unix[@]} Debian Red hat Ubuntu Fedora UTS OpenLinux Fri Feb 28 – 12:53 PM > echo ${#Unix[@]} 6 Fri Feb 28 – 12:53 PM > for index in “${!Unix[@]}” ; do printf “%4d: %s\n” $index “${Unix[$index]}” ; done 0: Debian 1: Red hat 2: Ubuntu 3: Fedora 4: UTS 5: OpenLinux

An alternate, perhaps simpler, method for removing an element, is to reassign Unix (making sure we include the quotes, as per previous post) from the remaining elements in the array (after unsetting): unset Unix[2] Unix=( “${Unix[@]” )

Example: —– $ Unix=(‘Debian’ ‘Red Hat’ ‘Ubuntu’ ‘SuSE’); —– $ echo “len: ${#Unix[@]}”; for ((i=0;i<4;i++)); do printf "%d %s\n" $i "${Unix[$i]}"; done len: 4 0 Debian 1 Red Hat 2 Ubuntu 3 SuSE —– $ unset Unix[2] —– $ echo "len: ${#Unix[@]}"; for ((i=0;i<4;i++)); do printf "%d %s\n" $i "${Unix[$i]}"; done len: 3 0 Debian 1 Red Hat 2 3 SuSE —– $ Unix=( "${Unix[@]}" ) —– $ echo "len: ${#Unix[@]}"; for ((i=0;i<4;i++)); do printf "%d %s\n" $i "${Unix[$i]}"; done len: 3 0 Debian 1 Red Hat 2 SuSE 3

(note that my loop runs past the end of the array after shortening it )

>>>There is no “DECLARED” maximum limit to the size of an array, …..

I need to quote, don’t you? Unix=( “${Unix[@]:0:$pos}” “${Unix[@]:$(($pos + 1)” )})

Also. in 11 declare -a patter=( “${Unix[@]/Red*/}” ) It doesn’t remove array elements, it removes the first occurrence that satisfies the regular expression inside each element in the array.

Choperro, actually: declare -a patter=( ā€œ${Unix[@]/Red*/}ā€ ) Removes all occurrences that satisfies the regular expression inside each element in the array.

$ Unix=(‘Debian’ ‘Red hat’ ‘Red Hat 2’ ‘Red Hat 3’ ‘Ubuntu’ ‘Suse’ ‘Fedora’ ‘UTS’ ‘OpenLinux’);

$ patter=( ${Unix[@]/Red*/} )

$ echo ${patter[@]} Debian Ubuntu Suse Fedora UTS OpenLinux

Thanks for a great tutorial!

I have a txt file with a list of directories that I hope to cd into, and do the same stuff for all of them. Suppose it look like this:

“/path/to/first/dir” “/path/to/second/dir” “/path/to/third/dir/with space” …

I try to use the code in your Example 15 for my purpose:

#!/bin/bash DIR=( `cat “$HOME/path/to/txt.txt” `) for t in “${DIR[@]}” do echo “$t” done echo “Done!”

The above script worked fine for the first and second directory, but the third one will output this:

“/path/to/third/dir/with space”

Instead of in one line. How can I fix that?

Also, if I add cd command in the above script:

#!/bin/bash DIR=( `cat “$HOME/path/to/txt.txt” `) for t in “${DIR[@]}” do echo “$t” cd “$t” done echo “Done!”

All the cd command would fail, the output looks like this:

“/path/to/first/dir” test.sh: line 6: cd: “/path/to/first/dir”: No such file or directory “/path/to/second/dir” test.sh: line 6: cd: “/path/to/second/dir”: No such file or directory “/path/to/third/dir/with test.sh: line 6: cd: “/path/to/third/dir/with: No such file or directory space” test.sh: line 6: cd: space”: No such file or directory

Could you shed some light on why this happened and how should I fix it? Thank you very much!

>> DIR=( `cat ā€œ$HOME/path/to/txt.txtā€ `)

That is always the wrong way to read a file; it reads it word by word not line by line.

In bash4, the easy way is to use mapfile:

mapfile -t dir < "$filename"

Thank you for the reply!

I changed my code to use the mapfile line you suggested.

But when I run the script, this is what I got:

./test.sh: line 3: mapfile: command not found

Any ideas? Thank you!

Ran into that recently porting some scripts from RedHat to Apple OS X Mavericks. Not all bash’s support mapfile (aka readarray); it’s there in RedHat, but not in Apple’s OS X. type “man mapfile” ; if it says “No manual entry” then your system probably doesn’t have mapfile implemented. In that case, you may need to do something like the following (someone smarter than me may have a better solution):

i=0 while read line do dir[$((i++))]=$line # store $line in dir[$i] and increment $i . . . done < $HOME/path/to/txt.txt

mapfile was introduced in bash4 ā€” more than 5 years ago.

Upgrgade your bash; it’s long overdue.

I just check my bash version in Mac OS X Mavericks: GNU bash, version 4.3.11(1)-release (x86_64-apple-darwin13.1.0)

Should it have mapfile?

I also tried the read line method Ian suggested. Thanks Ian btw!

However, I still ran into the same issue that all the “echo” command gave the correct results, but I can’t cd into all the directories.

Bash returned: “./test.sh: line 14: cd: “/Users/xiaoning/some/path”: No such file or directory”

Bash 4.3.xx does have mapfile. However, OS X Mavericks’ version of bash, which should be located in /bin/bash, is 3.2.xx . I suspect you have a 2nd version of bash installed, and this is getting invoked as your startup shell. (A likely location is /opt/local/bin/bash, which is where macports installs it if it is needed by any program installed by macports. Fink may do the same.)

Your reported version of bash, 4.3, should have mapfile, but /bin/bash under OS X does not, and your script specifies to run under /bin/bash (1st line of script). To use 4.3 in your script, Find where the bash you are running (“which bash” may tell you), and change the first line of your script to invoke that bash. For example (using my example):

#!/opt/local/bin/bash

Regarding why your script cannot cd to ā€œ/Users/xiaoning/some/pathā€ , I have no good explanation, assuming ā€œ/Users/xiaoning/some/pathā€ does exist. The command

ls -ld ā€œ/Users/xiaoning/some/pathā€

(from the command line) will verify that the directory exists.

mapfile is working now after changing the #! line to the macport bash I have installed.

Those are all valid directories that I can normally ls, or cd into. But the script for some reason is still not working…

The script I’m using now is to directly store the array of directories in a variable, and it worked just fine. However, when I try to read the same array from a file, it’s no longer working. Very strange…

how to remove lines containing any one of an array of strings from multiple files?

Using sed, write a script that takes a filename and a pattern to do the following. If the given pattern exists in the file with the very next line starting and ending with the same pattern, delete the line that starts and ends with the given pattern. please help

Thanks for tip no15. “Load Content of a File into an Array”. Exactly what I was looking for.

Care needs to be taken with quotes, both in general, and especially when playing with arrays. The following is a simple bash script that collects together working examples of the things you demonstrate above. Note that the file hx used at the end just contains a few lines of text, some of which contain spaces.

#!/bin/bash

declare -a A A[3]=flibble echo “$A[3]” might be flibble, the third item, but isnt echo “${A[3]}” should be flibble, the third item, note the braces echo “${A[@]}” is contents of array echo “${#A[@]}” is length of array echo “${#A[3]}” should be 7, length of flibble echo “${A[3]:2:3}” should be ibb, the three characters starting at pos 2 echo “${A[@]/ibb/bone}” is search and replace for each item A=(“${A[@]}” “wibble”) echo A is now “${A[@]}” echo now declare -a B=(“${A[@]}”) echo Third item is “${B[3]}” echo Zeroth item is “${B[0]}” echo So copying arrays this way does not preserve string keys — it reindexes declare -a C C[wibble]=wobble echo “${C[wibble]}” shows keys are strings, not contiguous integers declare -a D D=(“a b c d e” “c d f t g”) echo D is “${D[@]}” echo Length of D is “${#D[@]}” echo Length of “D[0]” is “${#D[0]}” echo “D[0] is ‘${D[0]}'” declare -a E=( ${D[@]} ) echo E is “${E[@]}” echo Length of E is “${#E[@]}” echo Length of “E[0]” is “${#E[0]}” echo “E[0] is ‘${E[0]}'” declare -a F=( ${D[@]/a*/} ) echo F is “${F[@]}” echo Length of F is “${#F[@]}” echo Length of “F[0]” is “${#F[0]}” echo “F[0] is ‘${F[0]}'” declare -a G=( “${D[@]/a*/}” ) echo G is “${G[@]}” echo Length of G is “${#G[@]}” echo Length of “G[0]” is “${#G[0]}” echo “G[0] is ‘${G[0]}'” echo Note in the above what happens with spaces echo To concatenate two arrays, preserving spaces, use double quoting declare -a H=(“${A[@]}” “${D[@]}”) declare -a I=(${A[@]} ${D[@]}) echo To delete an array use unset echo I is “${I[@]}” unset I echo I is now “${I[@]}” echo reading from a file px() { for s; do echo “$s”; done } echo version 1 declare -a I=(`cat hx`) px “${I[@]}” echo version 2 declare -a I=(“`cat hx`”) px “${I[@]}”

+1 on x31eq’s comment about the quoting. It also means the value of ${#Unix[@]} is wrong. It would be great if you could correct this.

I have a created 2 arrays A, B from command output

A=(`command1`) ## This contains filenames B=(`command2`) ## This contains DB names

Now I am issuing command3 using the above arrays

Example: unzip $A | mysql -u root -p $B ## Here the problem is it executes the ‘A’ portion for each of the ‘B’ elements

How do i solve this?

I have single item ‘red hat’ in array like array[‘red hat’]. I want split the array from single index to 2 indexes like array[‘red’ ‘hat’].please suggest me with a solution

I am trying to get the table value in an array. Say, there is a tbl with col1, col2, col3 having values ‘abc’, ‘def’, ‘ghi jkl’. There is a function that I use to get these values from my Table to a variable say DBVAL, which is echoed from the function. Now I want to assign each of these column values to different index of an array. currently the command I use is: declare -a arrayname=($(function_that_gets_value_from_table))

but if I do: echo ${#arrayname[@]} it gives: 4 instead of 3

and for arr in “${arrayname[@]}”; do; echo “$arr”; done gives: abc def ‘ghi jkl’ instead of: abc def ghi jkl

Even: arrayname=( $DBVAL ) does not work.

Although, if I declare the array with the hardcoded values (not get it from function/from any variable), then it works fine. declare -a arrayname=(‘abc’ ‘def’ ‘ghi jkl’) echo ${#arrayname[@]} gives: 3

for arr in “${arrayname[@]}”; do; echo “$arr”; done gives: abc def ghi jkl

Please help.

how to import multiple directory in array in runtime and check if directory is present or not ?

Thanks, this was a good beginning for me.

Very nice! By following your examples, I have successfully used arrays for many different automation scripts in bash. In the same light, I am now in need of having to print two different arrays of same length side by side onto a file. In other words, the first element of array A and the first element of array B should be on the first line of a text file separated by a tab. And so on. What’s the best way to achieve this?

I tried the following: printf ‘%s\t%s\n’ “${A[@]}” “${B[@]}” > file.txt

It didn’t do what I want. Instead, the above prints all elements of A first, then all elements of B, two per line.

Any pointers would be greatly appreciated!

Thanks! Nav

thankuuuuuuuu

Next post: Lzma Vs Bzip2 – Better Compression than bzip2 on UNIX / Linux

Previous post: VMware Virtualization Fundamentals – VMware Server and VMware ESXi

Linux 101 Hacks Book

  • Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
  • Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
  • Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
  • Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

POPULAR POSTS

  • 15 Essential Accessories for Your Nikon or Canon DSLR Camera
  • 12 Amazing and Essential Linux Books To Enrich Your Brain and Library
  • 50 UNIX / Linux Sysadmin Tutorials
  • 50 Most Frequently Used UNIX / Linux Commands (With Examples)
  • How To Be Productive and Get Things Done Using GTD
  • 30 Things To Do When you are Bored and have a Computer
  • Linux Directory Structure (File System Structure) Explained with Examples
  • Linux Crontab: 15 Awesome Cron Job Examples
  • Get a Grip on the Grep! ā€“ 15 Practical Grep Command Examples
  • Unix LS Command: 15 Practical Examples
  • 15 Examples To Master Linux Command Line History
  • Top 10 Open Source Bug Tracking System
  • Vi and Vim Macro Tutorial: How To Record and Play
  • Mommy, I found it! -- 15 Practical Linux Find Command Examples
  • 15 Awesome Gmail Tips and Tricks
  • 15 Awesome Google Search Tips and Tricks
  • RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
  • Can You Top This? 15 Practical Linux Top Command Examples
  • Top 5 Best System Monitoring Tools
  • Top 5 Best Linux OS Distributions
  • How To Monitor Remote Linux Host using Nagios 3.0
  • Awk Introduction Tutorial ā€“ 7 Awk Print Examples
  • How to Backup Linux? 15 rsync Command Examples
  • The Ultimate Wget Download Guide With 15 Awesome Examples
  • Top 5 Best Linux Text Editors
  • Packet Analyzer: 15 TCPDUMP Command Examples
  • 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
  • Unix Sed Tutorial: Advanced Sed Substitution Examples
  • UNIX / Linux: 10 Netstat Command Examples
  • The Ultimate Guide for Creating Strong Passwords
  • 6 Steps to Secure Your Home Wireless Network
  • Turbocharge PuTTY with 12 Powerful Add-Ons
  • Linux Tutorials
  • Sed Scripting
  • Awk Scripting
  • Bash Shell Scripting
  • Nagios Monitoring
  • IPTables Firewall
  • Apache Web Server
  • MySQL Database
  • Perl Programming
  • Google Tutorials
  • Ubuntu Tutorials
  • PostgreSQL DB
  • Hello World Examples
  • C Programming
  • C++ Programming
  • DELL Server Tutorials
  • Oracle Database
  • VMware Tutorials

About The Geek Stuff

Copyright Ā© 2008ā€“2023 Ramesh Natarajan. All rights reserved | Terms of Service

  • Getting started with Bash
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • Accessing Array Elements
  • Array Assignments
  • Array from string
  • Array insert function
  • Array Iteration
  • Array Length
  • Array Modification
  • Associative Arrays
  • Destroy, Delete, or Unset an Array
  • List of initialized indexes
  • Looping through an array
  • Reading an entire file into an array
  • Associative arrays
  • Avoiding date using printf
  • Bash Arithmetic
  • Bash history substitutions
  • Bash on Windows 10
  • Bash Parameter Expansion
  • Brace Expansion
  • Case statement
  • CGI Scripts
  • Chain of commands and operations
  • Change shell
  • Color script output (cross-platform)
  • Conditional Expressions
  • Control Structures
  • co-processes
  • Copying (cp)
  • Creating directories
  • Customizing PS1
  • Cut Command
  • Decoding URL
  • Design Patterns
  • File execution sequence
  • File Transfer using scp
  • getopts : smart positional-parameter parsing
  • global and local variables
  • Handling the system prompt
  • Here documents and here strings
  • Internal variables
  • Job Control
  • Jobs and Processes
  • Jobs at specific times
  • Keyboard shortcuts
  • Listing Files
  • Managing PATH environment variable
  • Navigating directories
  • Networking With Bash
  • Pattern matching and regular expressions
  • Process substitution
  • Programmable completion
  • Read a file (data stream, variable) line-by-line (and/or field-by-field)?
  • Redirection
  • Script shebang
  • Scripting with Parameters
  • Select keyword
  • Sleep utility
  • Splitting Files
  • The cut command
  • true, false and : commands
  • Type of Shells
  • Typing variables
  • Using "trap" to react to signals and system events
  • When to use eval
  • Word splitting

Bash Arrays Array Assignments

Fastest entity framework extensions.

List Assignment

If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces:

Create an array with new elements:

Subscript Assignment

Create an array with explicit element indices:

Assignment by index

Assignment by name (associative array)

Dynamic Assignment

Create an array from the output of other command, for example use seq to get a range from 1 to 10:

Assignment from script's input arguments:

Assignment within loops:

where $REPLY is always the current input

Got any Bash Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Bash Arrays: A Syntax and Use Cases Guide

Depiction of Bash array manipulation in a script with visual emphasis on array elements and programming logic

Are you finding it challenging to work with arrays in Bash scripting? You’re not alone. Many developers find themselves puzzled when it comes to handling arrays in Bash, but we’re here to help.

Think of Bash arrays as a well-organized bookshelf – allowing you to store and manage your data with ease. These arrays can help you manipulate data effectively, making Bash arrays a powerful tool for scripting tasks.

In this guide, we’ll walk you through the process of working with Bash arrays , from their creation, manipulation, and usage. We’ll cover everything from the basics of arrays to more advanced techniques, as well as alternative approaches.

Let’s get started!

TL;DR: How Do I Use Arrays in Bash?

To create an array in Bash, you can use the following syntax: array=(element1 element2 element3) . This command initializes an array with three elements.

Here’s a simple example:

In this example, we create an array named ‘array’ with three elements: ‘Apple’, ‘Banana’, and ‘Cherry’. Then, we print the second element of the array (remember, Bash arrays are zero-indexed, so index 1 corresponds to the second element). The output of this command is ‘Banana’.

This is a basic way to use arrays in Bash, but there’s much more to learn about creating and manipulating arrays in Bash. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Bash Array Basics: Creation, Access, and Modification

Advanced bash array operations, expert techniques: bash array slicing and indirect references, troubleshooting common bash array issues, understanding arrays in bash, bash arrays in larger scripts and projects, wrapping up: mastering bash arrays.

In Bash, creating an array is as simple as assigning values. You can create an array by assigning elements separated by spaces to a variable. Here’s how you do it:

In this example, we’ve created an array named ‘fruits’ with three elements: ‘Apple’, ‘Banana’, and ‘Cherry’. The echo ${fruits[*]} command prints all elements of the array.

Accessing Array Elements

To access an element from the array, you use the index of that element. Remember, Bash arrays are zero-indexed, meaning the first element is at index 0. Here’s how you can access an element:

In this example, ${fruits[0]} accesses the first element of the ‘fruits’ array, which is ‘Apple’.

Modifying Array Elements

Modifying an element in an array is as straightforward as accessing it. Here’s how you can change the value of an array element:

In this example, we replaced the second element ‘Banana’ with ‘Blueberry’. The echo ${fruits[*]} command then prints the updated array.

Understanding these basics of Bash arrays is crucial for managing and manipulating your data effectively in Bash scripting.

As you become more comfortable with Bash arrays, you can start to explore more complex operations. These include adding elements, deleting elements, and iterating over an array. Let’s dive in.

Adding Elements to an Array

Adding an element to a Bash array is simple. You can add an element to the end of the array using the following syntax:

In this example, we’ve added ‘Dragonfruit’ to the end of the ‘fruits’ array. The echo ${fruits[*]} command then prints the updated array.

Deleting Elements from an Array

Deleting an element from a Bash array is as simple as adding one. Here’s how you can delete an element from an array:

In this example, we used the unset command to remove the second element ‘Banana’ from the ‘fruits’ array. The echo ${fruits[*]} command then prints the updated array.

Iterating Over an Array

Finally, let’s discuss how to iterate over a Bash array. This is useful when you want to perform the same operation on each element of the array. Here’s an example:

In this example, we used a for loop to iterate over each element of the ‘fruits’ array. For each element, we printed a statement saying ‘I love [fruit]’. This is a powerful technique for processing arrays in Bash.

By mastering these advanced operations, you can manipulate Bash arrays to suit your needs and make your Bash scripts more powerful and flexible.

As you delve deeper into Bash scripting, you’ll find there are more advanced techniques for manipulating arrays. Let’s explore two such techniques: array slicing and indirect references.

Array Slicing in Bash

Array slicing is a method to retrieve a range of elements from an array. Here’s how you can slice an array in Bash:

In this example, we’ve created an array ‘fruits’ with five elements. The slice ${fruits[@]:1:3} retrieves three elements starting from index 1 (second element). The echo ${slice[*]} command then prints the sliced array. Array slicing is a powerful tool when you need to work with a subset of an array.

Indirect References in Bash

Indirect references allow you to use the value of a variable as the name of another variable. Here’s an example of how you can use indirect references with arrays in Bash:

In this example, we’ve created an array ‘fruits’ with three elements. We then set ‘index’ to 1 and ‘ref’ to ‘fruits[index]’. The ${!ref} syntax is an indirect reference that gets the value of the variable named by ‘ref’, which in this case is the second element of the ‘fruits’ array. The echo ${!ref} command then prints this element. Indirect references can be useful when you need to dynamically access array elements.

By leveraging these advanced techniques, you can manipulate Bash arrays in more sophisticated ways, making your Bash scripts even more flexible and powerful.

As with any programming concept, working with Bash arrays can sometimes be tricky. Let’s discuss a couple of common issues you may encounter, such as dealing with spaces in array elements and handling associative arrays.

Dealing with Spaces in Array Elements

Spaces can be a source of confusion when working with Bash arrays. If an element in your array contains a space, Bash may interpret it as a separate element. Here’s an example demonstrating this issue, and how to resolve it:

In this example, we intended ‘Yellow Banana’ to be a single element. However, Bash interpreted ‘Yellow’ and ‘Banana’ as separate elements because of the space. To avoid this, you should enclose elements with spaces in quotes:

Handling Associative Arrays

Bash also supports associative arrays, where you can use keys instead of indexes to access elements. Here’s an example of how to declare an associative array, and a common error you might encounter:

In this example, we declared an associative array ‘fruits’ with two elements: ‘color’ with a value of ‘Red’, and ‘name’ with a value of ‘Apple’. We then accessed the ‘name’ element using its key. Remember, when using associative arrays, you must declare them with declare -A before using them.

By being aware of these common issues and their solutions, you can avoid potential pitfalls and make your Bash scripting more effective.

Before we delve deeper into the usage of arrays in Bash, let’s take a step back and understand what an array is and why it’s so crucial in scripting and programming in general.

An array is a data structure that stores a collection of elements. These elements, also known as values, can be accessed by an index that points to a specific location in the array. Arrays can be visualized as a series of boxes, each holding a value, and each having a unique address (the index).

In the above code block, we’ve created an array named ‘fruits’ with three elements. Each element can be accessed using its index, which in Bash, starts at 0.

Arrays play a vital role in scripting and programming due to their versatility and efficiency. They allow programmers to store multiple values in a single variable, which can then be easily manipulated. This is particularly useful in situations where a script needs to handle a variable amount of data.

In Bash, arrays are not as powerful or as flexible as in other programming languages. However, they are still a valuable tool for handling lists of strings and can be used in a variety of ways to enhance your Bash scripts.

Bash arrays are not just useful for small scripts; they play a significant role in larger scripts and projects as well. The ability to store and manipulate sets of data is a fundamental requirement in many scripting scenarios, making Bash arrays an essential tool in a developer’s arsenal.

Exploring Related Concepts

As you become more comfortable with Bash arrays, you may want to explore related concepts. For instance, Bash associative arrays allow you to use arbitrary strings as array indices instead of just integers. This can be particularly useful when you need to map keys to values.

In this example, we’ve created an associative array ‘fruits’ with two elements. Each element is accessed using a string key instead of an integer index.

Bash doesn’t support multi-dimensional arrays directly, but there are ways to emulate them. This can be useful when you need to work with more complex data structures.

Lastly, Bash offers other data structures, such as strings and integers, which can be combined with arrays to create more complex and versatile scripts.

Further Resources for Mastering Bash Arrays

For those looking to delve deeper into Bash arrays and related topics, here are some valuable resources:

  • Advanced Bash-Scripting Guide : This guide provides an in-depth look at Bash scripting, including a detailed section on arrays.
  • GeeksforGeeks – Bash Scripting Array : This guide explores the topic of Bash scripting arrays, discussing various aspects and providing examples.
  • GNU Bash Manual : The official manual for Bash includes comprehensive information on arrays and other Bash features.

By exploring these resources and practicing with Bash arrays, you can enhance your Bash scripting skills and tackle more complex scripting challenges.

In this comprehensive guide, we’ve dissected the world of Bash arrays, a fundamental construct in Bash scripting. From basic creation and manipulation to advanced operations and alternative approaches, we’ve delved deep into the intricacies of Bash arrays.

We began with the basics, understanding how to create, access, and modify elements in Bash arrays. We then ventured into more advanced territory, exploring complex operations such as adding and deleting elements, and iterating over an array. We also uncovered expert techniques, including array slicing and indirect references, and how to leverage these techniques to manipulate Bash arrays in sophisticated ways.

Along the way, we tackled common challenges you might encounter when dealing with Bash arrays, such as handling spaces in array elements and working with associative arrays. We provided solutions to these issues, equipping you with the knowledge to overcome potential pitfalls.

Here’s a quick comparison of the methods we’ve discussed:

Whether you’re just starting out with Bash arrays, or you’re looking to level up your Bash scripting skills, we hope this guide has given you a deeper understanding of Bash arrays and their capabilities.

With the ability to effectively manage and manipulate data, Bash arrays are a powerful tool in any developer’s toolkit. Now, you’re well equipped to harness the power of Bash arrays in your scripts. Happy scripting!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Python requests library for POST request data submission code snippets Python logo

# Array Assignments

List Assignment

If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces:

Create an array with new elements:

Subscript Assignment

Create an array with explicit element indices:

Assignment by index

Assignment by name (associative array)

Dynamic Assignment

Create an array from the output of other command, for example use seq to get a range from 1 to 10:

Assignment from script's input arguments:

Assignment within loops:

where $REPLY is always the current input

# Accessing Array Elements

Print element at index 0

Print last element using substring expansion syntax

Print last element using subscript syntax

Print all elements, each quoted separately

Print all elements as a single quoted string

Print all elements from index 1, each quoted separately

Print 3 elements from index 1, each quoted separately

String Operations

If referring to a single element, string operations are permitted:

so ${array[$i]:N:M} gives out a string from the N th position (starting from 0) in the string ${array[$i]} with M following chars.

# Array Modification

Change Index

Initialize or update a particular element in the array

Modify array, adding elements to the end if no subscript is specified.

Replace the entire array with a new parameter list.

Add an element at the beginning:

Insert an element at a given index:

Delete array indexes using the unset builtin:

This works for sparse arrays as well.

Re-indexing an array

This can be useful if elements have been removed from an array, or if you're unsure whether there are gaps in the array. To recreate the indices without gaps:

# Array Length

${#array[@]} gives the length of the array ${array[@]} :

This works also with Strings in single elements:

# Array Iteration

Array iteration comes in two flavors, foreach and the classic for-loop:

# You can also iterate over the output of a command:

# associative arrays.

Declare an associative array

Declaring an associative array before initialization or use is mandatory.

Initialize elements

You can initialize elements one at a time as follows:

You can also initialize an entire associative array in a single statement:

Access an associative array element

Listing associative array keys

Listing associative array values

Iterate over associative array keys and values

Count associative array elements

# Looping through an array

Our example array:

Using a for..in loop:

Using C-style for loop:

Using while loop:

Using while loop with numerical conditional:

Using an until loop:

Using an until loop with numerical conditional:

# Destroy, Delete, or Unset an Array

To destroy, delete, or unset an array:

To destroy, delete, or unset a single array element:

# List of initialized indexes

Get the list of inialized indexes in an array

# Array from string

Each space in the string denotes a new item in the resulting array.

Similarly, other characters can be used for the delimiter.

# Reading an entire file into an array

Reading in a single step:

Reading in a loop:

Using mapfile or readarray (which are synonymous):

# Array insert function

This function will insert an element into an array at a given index:

ā† true, false and : commands Associative arrays ā†’

MarketSplash

How To Work With Bash Shell Array Basics

In the dynamic world of development, the Bash shell array stands out as a versatile tool. This article dissects its functionality, offering hands-on examples for operations such as declaring, initializing, and modifying arrays.

šŸ’” KEY INSIGHTS

  • Bash supports two types of arrays: Indexed and associative arrays offer flexibility in data management, enabling complex mappings and indexing in scripts.
  • Dynamic modification: Bash arrays allow for efficient data handling, with capabilities for altering, updating, or appending elements post-declaration, adapting to script evolution.
  • Element access nuances: Accessing data in Bash arrays involves simple syntax but varies between indexed and associative arrays, highlighting the importance of understanding different array structures.
  • Looping techniques: The article demonstrates effective methods for iterating through array elements, a crucial operation in Bash scripting for data manipulation.

Bash shell arrays offer a flexible way to manage and organize data. As one of the foundational structures in scripting, understanding their intricacies can amplify your coding efficiency. Let's explore how to effectively use and optimize them in your bash scripts.

bash array element assignment

Basics Of Bash Shell Arrays

Declaring and initializing arrays, accessing array elements, modifying and appending to arrays, looping through array elements, associative arrays in bash, common operations: slicing, searching, and sorting, frequently asked questions.

In the world of Bash scripting, arrays serve as a data structure to hold multiple values under a single name. They enable programmers to manage collections of data more effectively.

Types of Arrays in Bash

Syntax for declaring arrays, example of indexed arrays, example of associative arrays.

Bash supports two types of arrays:

  • Indexed arrays - This array type uses integers as its index. It's the most common array type in bash.
  • Associative arrays - This array allows you to use named keys instead of a simple index.

For indexed arrays :

For associative arrays :

Let's dive into a quick example:

In the above code:

  • We declared an indexed array named colors .
  • We accessed the second element using its index and printed the value 'blue'.

Now, let's see an example for associative arrays:

  • We declared an associative array named fruits .
  • Using keys (like 'apple' or 'banana'), we assigned values to the array.
  • We then accessed the value associated with the key 'apple' and printed 'tasty'.

Arrays are fundamental structures in Bash that can store multiple values. Whether you're dealing with strings or numbers, arrays efficiently manage these data collections. Let's break down how to declare and initialize these arrays.

Syntax for Declaring Indexed Arrays

Syntax for declaring associative arrays, initializing arrays after declaration.

The typical method for declaring an indexed array:

In the example:

  • An indexed array named sports is declared.
  • It's initialized with three string values.

Associative arrays, on the other hand, require a different approach:

In this example:

  • We initiate an associative array called countries .
  • We then use string keys (like 'USA' and 'UK') to define values in the array.

Sometimes, it's necessary to declare an array without initializing it immediately. For indexed arrays:

For associative arrays:

Notice in the code above:

  • We use the declare keyword to specify the type of array we're creating.
  • Initialization is done separately, giving you flexibility in your scripts.

Once you have declared and initialized arrays, the next logical step is accessing the stored data. Fetching values from arrays in Bash is quite straightforward, but there are nuances to bear in mind depending on the type of array you're working with.

Indexed Arrays

Associative arrays, accessing all elements.

To access an element from an indexed array, use the array name followed by the index in square brackets:

From the above:

  • We've defined an indexed array called days .
  • We accessed and printed the second element ( Tuesday ), using its index 1.

For associative arrays, the access mechanism is quite similar, but you'll use string keys instead of numerical indices:

In this snippet:

  • An associative array named capitals is utilized.
  • By referencing the key France , the corresponding value ( Paris ) gets printed.

Sometimes, you may wish to access all elements in an array:

  • The colors array contains three color names.
  • By using @ in square brackets, we printed all the elements.

Arrays are dynamic structures in Bash, which means you can easily change, update, or append to them post-declaration. The ease of modification is one of the aspects that makes arrays a preferred choice among Bash enthusiasts.

Modifying Indexed Arrays

Modifying associative arrays, appending to arrays.

To modify a specific element in an indexed array, use the array's name and the desired index:

In this instance:

  • We had an initial array fruits .
  • The second item ( orange ) was replaced with kiwi using its index.

Associative arrays work in a similar fashion, with the key being the distinguishing factor:

  • We initialized an associative array named vehicles .
  • The value associated with the key car was updated from sedan to SUV .

To add a new item to an indexed array, you don't need to specify an index:

In the code above:

  • We took our existing colors array.
  • A new color, yellow , was appended without needing an explicit index.

For associative arrays, appending is just like adding a new key-value pair:

  • We created a new associative array authors .
  • A new author, Austen , and her work, Pride and Prejudice , were added.

Iterating or looping through array elements is a common operation in Bash scripting. By doing so, you can manipulate, print, or perform actions on each item without explicitly referencing them.

Looping Through Indexed Arrays

Looping through associative arrays, using while and read for indexed arrays.

The most straightforward way to loop through indexed arrays is by using a for loop:

With the example:

  • The array numbers contains three elements.
  • Using the for loop, each element is printed sequentially.

Associative arrays require a slight tweak, primarily because you might want to loop through keys, values, or both:

An associative array named fruits is defined with two pairs.

A while loop combined with the read command provides another means to traverse indexed arrays:

  • We have a colors array with three elements.
  • By using the while loop and a counter variable index , each color is printed in sequence.

In Bash, associative arrays allow you to use non-integer keys, giving you the power to create more flexible data structures resembling dictionaries or maps in other languages. These arrays are key-value pairs where each key is unique.

Declaring Associative Arrays

Assigning key-value pairs, accessing values using keys, listing all keys and values.

To declare an associative array, you use the declare (or typeset ) command with the -A option:

  • We've initialized an empty associative array named animals .

You can assign values to keys using the following syntax:

  • The colors associative array has been populated with two key-value pairs.
  • apple is a key that corresponds to the value red .

To retrieve a value associated with a key, use this syntax:

  • The value associated with the key apple is retrieved and printed.

Often, you might want to get all keys or values from the array:

  • We loop through all the keys in the colors array.
  • For each key, we access its corresponding value with ${colors[$key]} .

Array Slicing

Searching in arrays, sorting arrays.

Slicing allows you to extract a portion of an array. In Bash, you can slice an array using the following syntax:

This will output:

banana cherry date

To search for an element, you can loop through the array and compare values.

  • We search for the string "cherry" in the fruits array.
  • If found, a message is displayed.

Bash does not have a built-in array sorting mechanism, but you can use external commands like sort .

apple banana cherry date fig

  • The fruits array is converted to a multi-line string and then sorted using the sort command.
  • The sorted list is then read back into a new array sorted_fruits .

What is a Bash shell array?

A Bash shell array is a data structure that allows you to store multiple values, possibly of different data types, under a single variable name. Arrays are zero-indexed, which means the first item is accessed with an index of 0.

Can Bash support associative arrays?

Yes, Bash version 4 and above supports associative arrays. You can declare an associative array using declare -A and then assign key-value pairs to it.

Are associative arrays supported in Bash?

Yes, Bash supports associative arrays, where you can assign values to a specific key instead of an index. Declare an associative array with declare -A array_name , and add elements using the syntax array_name[key]=value .

Can I sort an array in Bash?

Bash does not provide a built-in way to sort arrays, but you can use external commands like sort to sort the output of your array elements.

Letā€™s test your knowledge!

Which Command In Bash Will Print All Elements Of An Array Named 'arr'?

Continue learning with these bash shell guides.

  • Understanding The Distinction Between Bash And Shell
  • Bash Shell Testing: Strategies And Best Practices
  • How To Use Synology Bash Shell Effectively
  • Bash Shell Commands: A Comprehensive Guide For Beginners And Experts
  • Bash Shell Functions: A Comprehensive Guide

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

LinuxSimply

Home > Bash Scripting Tutorial > Bash Array > Declare Array in Bash [Create, Initialize]

Declare Array in Bash [Create, Initialize]

Md Masrur Ul Alam

Bash , a widely popular and powerful shell in the world of Linux, offers diversified ways to ensure efficient data management and arrays are tools as such. However, before diving into the scripting universe, one must have complete knowledge of how to declare an array in Bash and createĀ and initialize it. Henceforth, in this article, I have undertaken a plan to enlighten you on these quintessential concepts for data storage and manipulation in Bash scripting .

How to Declare, Create, and Initialize Arrays in Bash?

You can declare , create , or initialize Bash arrays by exploiting some simple syntax. See the syntax given below:

  • To declare a bash array use the declare command: declare -a array1
  • To create a bash array use parentheses: array2=()
  • To initialize a bash array insert elements inside the parentheses: my_array3=(value)

What is Array Declaration, Creation, and Initialization in Bash?

The terms ā€œarray declaration,ā€ ā€œarray creationā€ , and ā€œarray initializationā€, each have a distinctive definition in the context of programming languages. First, letā€™s explore their definition:

  • Declaration of an Array: The declaration specifies the array variable with a name and sometimes, type and it does not necessarily allocate space in memory.
  • Creation of an Array: To create an array, means to allocate memory for the and prepare it to hold values of specified types and may not involve the initialization of values at the beginning.
  • Initialization of an Array: The initialization of an array is to provide the array with elements to store just after it is constructed.

However, considering the differences, it is crucial to acknowledge that, in the context of Bash arrays , they are essentially the same thing and you can use the terms interchangeably in working with the arrays. To grasp a clearer gist, follow the article till the end.

Array Declaration in Bash

The declaration can be termed the foremost step when you intend to work with arrays in Bash though it is not mandatory since Bash is a dynamically typed scripting language. Still, you can practice the standard process of declaration that alerts the system of your intention to work with a variable which is an array type. Therefore, in this feature, I will cover the necessary particulars related to declaring a Bash array (both the indexed and associative arrays) .

A. Declare an Indexed Array in Bash

An indexed array form references the data elements using indices starting from ā€˜0ā€™. So, if an array contains two elements, the first value is placed at index 0 while the second element (last element) is at index 1. Declaring an indexed array in Bash involves a few super simple steps. Thus, the agenda of this section will primarily be to introduce you to the ways you can declare an indexed array. Specifically, I will cover the explicit , indirect , and compound assignment methods.

Method 01: Declare an Indexed Array in Bash with Explicit Method

In this method, you first declare the array that you want to work with by mentioning its type in an explicit manner . However, in Bash, there is no need for this direct declaration since it specifies the array as indexed by default . Nevertheless, you can still use the declare command and following scripting syntax like the following:

  • declare : Bash command used to explicitly set the array variable attribute.
  • -a: Option indicating the declaration of an indexed array .
  • <array_name>: The name you want to assign to the array.

Itā€™s really that simple. Now, follow a bit further for demonstration where I will declare an empty array named tools . For that see the below Bash script:

In the first line of the script, #!/bin/bash , #! is called shebang . It indicates the system uses the bash interpreter for executing the script. Then, in the 3rd line,Ā  I used the declare command with the -a option to declare the array named tools in an explicit manner. Finally, I used the echo command to print a message denoting the declaration of the tools array with no issue.

indexed array declare in Bash with create initialize.

Note: You can also declare an empty array like the following:

Method 02: Declare an Indexed Array in Bash with an Indirect Method

The above scope showed how you can explicitly declare an indexed array in Bash. However, you can also handle the Bash array declaration in an implicit manner . Just assign values to the respective indices using the following line of code and Bash will automatically declare the array. The syntactic details are mentioned below:

  • array_name: The name of the array you assign.
  • position: The index at which you want to assign value.
  • value: The item you insert to the specified index.

Following this, I will display the practical aspects using the below script where I will create an array called first_name utilizing the aforementioned syntax:

In the script, I directly assigned elements to the Ā first_name array without declaring it. In consequence, this declares the array in the system which is evident in the last line of the code where I used the echo command and printed that I have declared the array first_name with no explicit mention.

indirect indexed array declaration in Bash and create initialize.

Method 03: Declare an Indexed Array in Bash Using Compound Assignment

The compound assignment technique is generally to modify the existing state of an array by the use of compound operators (addition, subtraction, etc., followed by the assignment operator =) . Nonetheless, in this case, you can use the =+ operator to add elements to an array and end up, eventually, declaring it. Now, if the array does not exist, Bash declares it. The command is:

  • +=: Compound operator to add array elements.

Now, follow this script to get a more comprehensive idea of the above method of declaration:

In the above script, I made use of the compound += operator to declare the indexed array last_name . In this proceeding, I added 3 elements to the array which automatically declared this new array as it was not extant in the system. Finally, I printed that I completed the array declaration to the terminal using the echo command .

index array declare in bash and create initialize using compound assignment.

B. Declare an Associative Array in Bash

Likewise, you can accomplish the associative array declaration in Bash using the declare command . This sets the array type explicitly as associative . The super simple command to declare the array is as follows:

  • declare: Bash command used to set the array variable attribute.
  • -A: Option indicating the declaration of an associative array.
  • <associative_array_name>: The name you want to assign to the array.

Furthermore, you can declare an associative array in Bash via value assignment through keys (also called string indices ). See the syntax below:

At this point, I will declare two associative arrays in the following script to display the methods:

The aforementioned bash script shows that I declared an empty associative array and named it cricket . I used the -A option to notify that I intended to declare a Bash array which is associative in nature. Then, I also declared an array named players and added some values to it. Finally, I printed that I declared the arrays using two echo commands after each line of array declaration.

associative array declaration in bash and create initialize.

This screenshot denotes that I have declared two associative arrays using the script.

Note: Donā€™t forget to declare an associative array with declare -A command nor Bash will treat it as an indexed array .

Array Creation in Bash

Now that you have grasped the basics of bash array declaration, let me redirect the discussion to c reating an array in Bash. Array creation in Bash necessarily revolves around the allocation of memory along with preparing it to hold values. However, one key thing to remember is that the array creation happens simultaneously with the array declaration. Therefore, reviving the declaration concepts will seamlessly introduce you to array creation in Bash and the next section serves that purpose for both the indexed and associative arrays .

A. Create an Indexed Array in Bash

You can create a Bash array in the similar manner you declared them in the former section. Letā€™s reiterate together. Here, I will mention both the direct and indirect methods.

Method 01: Using Direct Methods to Create an Indexed Array in Bash

The explicit declaration using the declare -a command and array defining with value assignment both fall into the category of direct methods to create an indexed array in Bash. The standard syntaxes are:

Now, I will develop a script to create two arrays and print their lengths to show you the gist:

I used the above bash script to create the arrays opponents and hello . In the first case, I used the declare command to declare and create the array opponents (though empty ) at the same time. In the second case, I assigned names as well as values to the hello array. Finally, I printed the array lengths using the echo ${#the_array[@]} (Here, ${} is used to retrieve the value of a variable, the_array is the name of the array you want to assign, and [@] points out the referencing of all elements of the array) expression to state that I created the arrays successfully.

index array creation in bash.

Method 02: Using the Indirect Method to Create an Indexed Array in Bash

Additionally, you can just assign values to an array of your choice indirectly creating an array. Navigate to the following and utilize the command:

  • array_name: The array name of your choice.
  • [index]: Points out the elements at the index.
  • element: the element located at the index.

To develop an array called flowers and print the elements seeĀ the below Bash script:

In this script, I directly assigned 3 values to an array that I wished to name flowers using their positional keys (indices) . This eventually helped me create the array and I was able to print all the elements using the expression echo ${flowers[@]} .

bash array declaration with creation using item assignment.

B. Create an Associative array in Bash

In Bash, creating the associative arrays is very straightforward demanding a few lines of code. In the next feature, I will walk you through the several ways you can adopt to create bash associative arrays filling your requirements.

Method 01: Using the Explicit Commands to Create a Bash Associative Array

There are two commands namely declare and typeset that you can make responsible for the Bash associative array creation. Of them, you already have seen the use case of the declare command in bash array declaration. Similarly, syntax using the typeset command is also afoot.

Now, see the below Bash script for more in-depth intuition:

In developing the aforementioned script, I created 2 associative arrays . In the 4th line, I used the declare command while I used the typeset command, in line number 9 , and created the arrays employee and employer respectively. Finally, I used the echo commands to show that I created the arrays with success.

associative array creation in bash.

Method 02: Utilizing Item Assignment to Create a Bash Associative Array

Similarly, you can create a Bash associative array through item assignment . It refers to the creation of an array by adding a set of elements in the respective positions using keys (string indices) . To implement, simply add the following line and you are good to go:

In the following, I will create an array named movies as a quick demonstration:

In this Bash script, I created an associative array using the declare command and simultaneously inserted values using keys (string indices) . As a result, this item assignment along with declaring the array explicitly creates the array. Finally, the echo command denotes that the code is correct and I was able to create the array using the item assignment method.

associative array creation in bash using item assignment.

Array Initialization in Bash

The initialization of a Bash array means setting up its initial values. This you can do at the time of array declaration/creation or later by providing the initial values for the array to store. Now, in this scope, I will shed light on the various ways you can initialize a bash array (both the indexed and associative array) seamlessly. So, letā€™s dive in.

A. Initialize a Bash Indexed Array

This section revolves around the various tips and tricks you can follow to initialize an indexed array in Bash. Specifically, I have discussed the index-based and loop-based methods for array initialization. So, without delay, letā€™s jump right in.

Method 01: Using Indices to Initialize an Indexed Array with Elements In Bash

The indexed arrays store values using indices that are 0-based . Now, you can exploit them to initialize the Bash array with elements. This is also referred to as item assignment .Ā  On top of that, due to its vibrant nature, you can initialize elements in places that are not contiguous in the array.

At this point, follow the below script to initialize an array using indices:

In this script, I initialized two index arrays topOrder and middleOrder with values at the beginning of array creation. Moreover, I initialized the arrays by adding elements both with and without in a sequential manner (array topOrder and middleOrder respectively) . Finally, I used the echo command and printed a message to show that I seamlessly initialized arrays.

array declaration in bash with initialization.

Method 02: Applying for Loop to Initialize an Indexed Array in Bash

Accessing array elements using loops is a very common practice among programmers. However, this technique can also come in handy at the time of array initialization. Therefore, see the below script to loop through an array to initialize it:

In this aforestated Bash script, first, I declared and created the array numbers . Then, I used the for loop to iterate the array 5 times and initialize it with 5 values . Finally, The echo command and for loop displayed the initialized values to the terminal.

array declaration in bash with initialization using for loop.

B. Initialize a Bash Associative Array

Initialization of Bash associative array is possible to achieve in several ways. In the following section, I will mention two methods (using item assignment and for loop ).

Method 01: Availing Item Assignment to Initialize an Associative Array in Bash

Using item assignment , you can initialize an associative Bash array. Just after the declaration or the array creation, you have to define the keys and insert values to the keys and you are done.

To create an array called results and initialize it to store values, go through the below script:

I used the above script to declare an associative array namely results . At the same time, I also populated it with 2 elements. Finally, I printed the 1st initialized element using the expression echo ā€œ${results[match1]}ā€ .

associative array initialization using item assignment.

Similarly, you can initialize the array later after the declaration:

In this script, I declared the my_associative_array explicitly. Then, I initialized it with 3 values to store as a starting point of data storage. Finally, I utilized the echo command to print 2 values to the terminal.

array initialization after creation.

Method 02: Employing for Loop to Initialize an Associative Array in Bash

Like indexed arrays, you can also initialize the associative array using a for loop . Below, I will create an array and initialize it via the looping process:

Here, in this Bash script, I created an associative array namely runs . Then, I created two array s to store the keys and values of the runs array. After that, I exploited a for loop to assign the keys and the respective values to the array (For every key, the values are stored in the keys and both are sequentially stored in the array runs ). Finally, I used the echo command to check for the initialization and I came out successful.

associative array initialization using for loop.

Note: In the above, scrutiny lets you discern that creating, declaring, or initializing a Bash array can refer to the same phenomenon which is why the overlapping of methods is strongly visible. In fact, the below lines of code simultaneously declare, create, and initialize Bash arrays.

Looks familiar, right?

In this article, I have discussed Bash array handling in terms of array declaration, creation, and initialization with values. Moreover, I have attached numerous practical cases through script development. I hope this compact package will aid your learning of Bash arrays and elevate your level of becoming a quality Bash scripter.

People Also Ask

How to initialize an array with elements.

To initialize a bash array, insert elements inside the parentheses like this syntax: my_array=(value) .

Do Bash arrays start with 0 or 1?

The Bash arrays, especially, the indexed arrays are 0-index-based arrays means they start with 0 . Since their indexing begins with 0 and increments by 1 with each element addition to the arrays.

How to declare an empty array in Bash?

To declare an empty array in Bash, you can use the declare command , simply useĀ the syntax, declare -a/A <array_name> . ItĀ creates an empty indexed/associative array and you can assign values later.

Do array declaration and creation differ in Bash?

Yes , in Bash, array declaration and creation are related and often interchangeable. The declaration involves the specification of an array-type variable. This declaration also is responsible for the creation of an array in Bash via dynamically allocating memory .

Is it necessary to declare the array size in Bash?

NO , in Bash, you need not define the array size explicitly. Rather, Bash arrays are dynamic . There is no limitation in terms of adding elements and the length is dynamically adjusted.

How to declare an array in Bash?

To declare an array in Bash, use the syntax: array_name=(element1 element2) . This will create an array called array_name with 2 items element1 and element2 .

Related Articles

  • How to Read into Bash Array [3 Methods]
  • Index Array in Bash [Explained]
  • Bash Associative Arrays [Explained]
  • Bash Array of Arrays [Explained]
  • Elements of Bash Array

<< Go Back to Bash Array | Bash Scripting Tutorial

icon linux

Md Masrur Ul Alam

Assalamu Alaikum, Iā€™m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

IMAGES

  1. How to Use Arrays in Bash Shell Scripts

    bash array element assignment

  2. Learning Bash Arrays

    bash array element assignment

  3. How to Use Arrays in Bash Shell Scripts

    bash array element assignment

  4. How to use arrays in Bash

    bash array element assignment

  5. BASH tutorials

    bash array element assignment

  6. Full Guide to Bash Arrays

    bash array element assignment

VIDEO

  1. Working with BASH shell

  2. Element rc knightwalker snow bash!

  3. Indium Element Assignment Chemistry SK015

  4. How to use Destructuring Assignment in JavaScript

  5. Azure User Story Assignment

  6. Unix: Bash mapfile array count different

COMMENTS

  1. How to Use Arrays in Bash Shell Scripts

    You can also update the value of any element of an array; for example, you can change the value of the first element of the files array to "a.txt" using the following assignment: files[0]="a.txt" Adding array elements in bash. Let's create an array that contains the name of the popular Linux distributions: distros=("Ubuntu" "Red Hat ...

  2. How can I assign a value to an array in Bash?

    There are a few syntax errors here, but the clear problem is that the assignments are happening, but you're in an implied subshell.By using a pipe, you've created a subshell for the entire while statement. When the while statement is done, the subshell exits and your Unix_Array ceases to exist.. In this case, the simplest fix is not to use a pipe:

  3. Arrays (Bash Reference Manual)

    6.7 Arrays. Bash provides one-dimensional indexed and associative array variables. ... When assigning to indexed arrays, if the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. ... Individual array elements may be assigned to using the ...

  4. Introduction to Bash Array

    Notably, the array elements are subject to further word splitting when using the unquoted construct. 4.2. Transforming Arrays ... Thus, we can perform lower-case to upper-case transformations and vice-versa with the Bash arrays. 4.3. Assignment Between Arrays. In the previous transformation examples, the initial array wasn't modified. ...

  5. Elements of Bash Array

    The index assignment syntax array_name[index]=element adds a new element to an existing Bash array in any specified index. I'll use the same dept array to add 2 new elements Arch and CEE at index 2 and index 10 using the index assignment syntaxes dept[2]=Arch and dept[10]=CEE .

  6. Bash Array Explained: A Complete Guide

    Update array elements. Loop through a Bash array using either the elements or the indexes. Create indexed and associative arrays using the declare builtin. Append elements to an existing array. Remove elements from an array or delete the entire array. Remove duplicates from an array. Check if an array contains an element that matches a specific ...

  7. A Complete Guide on How To Use Bash Arrays

    You can create an Indexed Array on the fly in Bash using compound assignment or by using the builtin command declare. The += operator allows you to append a value to an indexed Bash array. ... The second option to shuffle the elements of a bash array is to implement an unbiased algorithm like the Fisher-Yates shuffle. The challenge to implement ...

  8. How to use bash array in a shell script

    Create indexed or associative arrays by using declare. We can explicitly create an array by using the declare command: $ declare -a my_array. Declare, in bash, it's used to set variables and attributes. In this case, since we provided the -a option, an indexed array has been created with the my_array name.

  9. Bash Array

    What is an Array in Bash? In Bash, an array is a collection of values. It's a list containing multiple values under a single variable entity. The array values are typically called elements managed and referenced in an indexed approach.Unlike programming languages such as C or C++, bash arrays function as the one-dimensional storage of diversified data types.

  10. Bash Arrays Explained: A Simple Guide With Examples

    Bash has two types of arrays: indexed arrays and associative arrays. For indexed arrays, the indexes begin from 0 to (n-1), as is common in most languages. However, arrays in Bash are sparse. This means that you can assign the (n-1)th array element without having assigned the (n-2)th element. In this tutorial, you will learn how to work with ...

  11. The Ultimate Bash Array Tutorial with 15 Examples

    1. Declaring an Array and Assigning values. In bash, array is created automatically when a variable is used in the format like, name[index]=value. name is any name for an array; index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.

  12. bash

    I'm trying to figure out like three or four things at the same time.The most I need help with is how to get the greatest number in all the files that I have created on a prior run of my script, that created a new file with a (int) identifier. to separate all of the files that have no metadata, to single them out to keep all of them from being over written because as I'm storing them all in the ...

  13. Bash Tutorial => Array Assignments

    Learn Bash - Array Assignments. Example. List Assignment. If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces:

  14. Bash Arrays: A Syntax and Use Cases Guide

    In Bash, creating an array is as simple as assigning values. You can create an array by assigning elements separated by spaces to a variable. Here's how you do it: ... Deleting an element from a Bash array is as simple as adding one. Here's how you can delete an element from an array: fruits=('Apple' 'Banana' 'Cherry') unset fruits[1] echo ...

  15. Bash

    #Arrays # Array Assignments List Assignment. If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces:

  16. How To Work With Bash Shell Array Basics

    šŸ’” KEY INSIGHTS; Bash supports two types of arrays: Indexed and associative arrays offer flexibility in data management, enabling complex mappings and indexing in scripts. Dynamic modification: Bash arrays allow for efficient data handling, with capabilities for altering, updating, or appending elements post-declaration, adapting to script evolution. ...

  17. Assigning the value of an array to a variable bash script

    I want to ask about the syntax i use to assign a value of a two dimensional array element to a variable. this is basically what i am trying to do: I have a 2 dimensional array of characters and a string called sub_string that gets the value of a particular element in the array and put it in another string called whole_string

  18. bash

    Since you did not declare foo as an associative array, your code sets foo[0] to baz. It sets index zero because bar is being used in an arithmetic context (since it's an ordinary array assignment). Your bar variable, used as an index in an ordinary array, either has the value zero, or it is unset (does not exist).

  19. Declare Array in Bash [Create, Initialize]

    Method 01: Using Indices to Initialize an Indexed Array with Elements In Bash. The indexed arrays store values using indices that are 0-based. Now, you can exploit them to initialize the Bash array with elements. This is also referred to as item assignment. On top of that, due to its vibrant nature, you can initialize elements in places that ...

  20. shell

    I'm having a trouble getting this working in bash, I have the following array. server-farm=("10..10.1" 10.0.10.2") I would like to loop through this array and assign uniq variable to each element. Desired results. srv1 = 10.0.10.1 srv2 = 10.0.10.2 Is this possible? This is what I have tried so far, but couldn't get it to work.

  21. Passing arrays as parameters in bash

    Then, passing arrays by value to functions and assigning one array to another would work as the rest of the shell syntax dictates. But because they didn't do this right, ... # Print all elements of two bash arrays, plus two extra args at the end. # General form (notice length MUST come before the array in order # to be able to parse the args ...

  22. Assign Element of Array to Variable Bash

    bash assign variable to array elements. 0. Assign value to array in bash. 0. shell script assigning value of array to variables. 1. Assign variable on array with loop in Bash Script. 2. BASH assign value in an ARRAY dynamically. Hot Network Questions What effect do caves have on music played in them?