Master Bash Array of Strings with Spaces [Complete Guide]

You can use the following syntax to work with a Bash array of strings with spaces:

  1. To declare the array: declare -a array=("element with space")
  2. To print the array: echo "${array[@]}"
  3. To append to array: array+=("element of string with space")
  4. To remove an element: unset array[index of element with space]
  5. To iterate over the array using for loop: for element in "${array[@]}"; do
    # commands to execute; done

In working with Bash arrays, one may come across “elements of strings containing spaces” in which the individual elements have multiple space-separated strings. An array with such contents can present unique challenges in data handling and manipulation within arrays. So, this article provides an in-depth discussion on arrays in Bash containing elements of strings with spaces. It will mention fundamental concepts such as declaring arrays, adding, removing elements, and iterating over them to printing array contents including standard syntax and Bash script development along with mentioning common challenges in with arrays of strings with spaces and solutions.

1. Declaring Array of Strings with Spaces in Bash

The foremost step in working with an array in Bash is to declare it. The declare -a command can be used for the explicit declaration of an array with the initialization of elements of strings containing spaces. The full syntax to follow is declare -a array_name=("elements"). Below is an example:

#!/bin/bash

# Define an array with elements containing spaces
declare -a names=("roger federer" "rafeal nadal" "novak djokovic")

# Print the entire array
echo "Array elements with spaces:"
echo "${names[@]}"
EXPLANATION

In the script, the command “declare -a” command declares a Bash array with 3 elements that are strings containing multiple words with spaces. The echo command is used to print the array using echo "${names[@]}".

declare array of strings with spaces
Note: To declare an array with elements containing spaces without the “declare” command, use the syntax array=("elements with spaces")

2. Printing the Array Elements of Strings with Spaces

Printing the elements of an array is a common operation in dealing with arrays in Bash. Thus, to print the Bash arrays of individual elements of strings with spaces, the expressions ${array[@]}” and ${array[*]}” both are the most popular to use with the echo command.

Here’s an example to print arrays in Bash with elements of strings with spaces:

#!/bin/bash

#Array creation with elements containing spaces 
black=("jon kabir" "tahsan khan" "afridy tony" "khademul jahan")

#printing array length to the terminal using both expressions
echo "the array elements printed using \${black[@]}: ${black[@]}"
echo               # for adding extra spaces between the outputs
echo "the array elements printed using \${black[*]}: ${black[*]}"
EXPLANATION

In the script above, an array black is created with 4 elements using the expression black=("jon kabir" "tahsan khan" "afridy tony" "khademul jahan") in which all the elements are multi-word strings separated by space. Then the expressions ${black[@]} and ${black[*]} both expand the array elements and the echo command prints them on the terminal.

print the array elements containing spaces

Printing the Array Length

To print the length of a Bash array with elements of string type containing spaces, use the syntax echo ${#array[@]} where hash # is used for parameter expansion to get the number of elements of the given array.

Below is an example of printing the length of a Bash array of strings with spaces:

#!/bin/bash

# Define an array with elements containing spaces
my_array=("big apple" "medium pizza" "small town")

# Print the entire array using ${my_array[@]}
echo "elements of array: ${my_array[@]}"
#print array length:
echo "length of array: ${#my_array[@]}"
EXPLANATION

In the script, there is an array called my_array with three elements that are multi-word space separated strings. Now, the code  ${#my_array[@]} expands the array and the hash sign takes the number of array elements (the array length) and prints using the “echo” command.

print array length

3. Accessing the Elements Containing Spaces

Accessing the array elements in Bash is crucial for printing the elements as well as manipulating the array. The most simple method to access the array elements and print is to use the syntax echo "${array[index_num]}" where index_num is the element index to access (index 0 means 1st element for example). Here’s how:

#!/bin/bash

# Define an array with elements containing spaces
my_array=("apple pie" "banana shake" "red wine")

# Access individual elements of the array
echo "Accessing individual elements:"
echo "First element: ${my_array[0]}"
echo "Third element: ${my_array[2]}"
EXPLANATION

In the script, the expression my_array=("apple pie" "banana shake" "red wine") initializes an array called my_array with 3 items. The expressions ${my_array[0]} and ${my_array[2]} access the elements at indices 0 and 2 (1st and 3rd element) and the echo command prints them on the screen. The final result denotes that the array elements of strings with spaces have been displayed with success on the screen.

access spaces separated elements of strings

4. Iterating Over the Elements of Strings with Spaces

It is possible to iterate over the array elements of strings with spaces using loops such as the Bash for loop. This provides an iterative approach to access the array and manipulate it as needed using the syntax for element in "${array[@]}".

Below is an example of iterating a Bash array of strings with spaces using a Bash for loop:

#!/bin/bash

# Define an array with elements containing spaces
array=("virat kohli" "tamim iqbal" "dale steyn")
# Iterate over each element in the array

echo "Iterating over array elements:"
for element in "${array[@]}"; do
    echo "$element"
done
EXPLANATION

In the above script, the command array=("virat kohli" "tamim iqbal" "dale steyn") creates an array with 3 elements. Then the loop for element in "${array[@]}" iterates over the array and prints them in new lines iteratively which are elements string in nature with spaces.

iterate over the array

5. Appending Element with Spaces to an Array

To append an element to a Bash array is to add a new element to the end of the array by default. So, to append elements of strings containing spaces, the syntax array+=("string with space") is enough. Here’s how:

#!/bin/bash

#The main array
theatre=("mike portnoy" "john petrucci" "jordan rudes")

#prints array with 3 existing elements
echo "array before appending: ${theatre[@]}"
#new value to append
theatre+=("john myung")
echo 

#Prints array with newly added element four
echo "array after appending: ${theatre[@]}"
EXPLANATION

In the script, after declaring an array theatre, the expression theatre+=("john myung") appends a new array element of a string containing spaces to the array. Finally, the echo command prints the array twice to show elements and reflect on the changes after the appending operation.

append elements to array

6. Inserting Array Elements

The append operation inserts elements to an array to the end by default. However, it is possible to insert elements of strings with spaces to a specified index by availing the array insertion operation using the simple syntax array[index]="element to insert". Here’s an example:

#!/bin/bash

# Define an array with elements containing spaces
array=("andy murray" "maria sharapova" "andy roddick")

#insert array element:
array[3]="serena williams"
# Iterate over each element in the array
echo "elements after insertion:"
for element in "${array[@]}"; do
    echo "$element"
done

# Iterate over each element in the array and find the index of "serena williams"
for i in "${!array[@]}"; do
    if [[ "${array[$i]}" == "serena williams" ]]; then
        echo "Index of 'serena williams': $i"
        break
    fi
done
EXPLANATION

Here, the above script first initializes a Bash indexed array with 3 elements of strings containing spaces. Then, to insert another value of strings of such type, it uses array[3]="serena williams" expression to insert the multi-word string “serena williams” at index 3 (4th position) as an element that is seen after printing the array elements in new lines using a for loop.

insert element to array
Note: The above also lets you append to an array at a specified index just like the above example which you should have understood by now.

7. Delete Array Elements with Spaces in Bash

To delete array elements that seem unnecessary, use the “unset” command with the syntactical format unset array[index]. This deletes the array element located at the index.

Let’s see the unset command in action to delete array elements of strings containing spaces:

#!/bin/bash

# Define an array
my_array=("mark zuckerberg" "nikola tesla" "christian bale")
# Print the array
echo "${my_array[@]}"

# Use unset to remove array item
unset my_array[0]
# Print the array and length
echo "after element removal: ${my_array[@]}"
echo "length: ${#my_array[@]}"
EXPLANATION

In the script, after declaring the array named my_array with 3 multi-word elements with spaces, the command unset my_array[0] removes the element “mark zuckerberg”. After printing the array and its length, the changes in the array are seen.

delete array items

Pitfall: Not Enclosing Elements Containing Spaces with Quotes

This section will mention 1 common pitfall that may arise in working with array elements containing spaces. So, let’s discuss the potential pitfall and how to resolve it:

The common challenge that arises in handling array elements of strings with spaces is not to accidentally enclose the elements within quotes (single or double). This leads Bash to treat the element as multiple elements of the array since it uses spaces primarily to separate elements in an array.  See the following script:

#!/bin/bash

#array declaration and initialization
players=(leo messi "zinedin zidan" "christiano ronaldo")
echo "length: ${#players[*]}"

# Output:
# 4 but the length should be 3.

The above script has one element (leo messi) without quotes, and Bash treats it as 2 elements instead of a single element. That’s why it prints the array length as 4 while it should have printed 3 as the array length.

Solution: Deal with Spaces Using Quotes Around Array Elements

The solution to the above issue is always to enclose the elements containing spaces with double (“”) or single (‘’) quotes to ensure that they are treated as single elements.

Now, see the revised version of the above example for clarification:

#!/bin/bash

players=("leo messi" "zinedin zidan" "christiano ronaldo")
echo "length: ${#players[*]}"

# Output: 3

Conclusion

The above article discusses the ins and outs of a Bash array that contains elements that are strings containing spaces. It mentions different methods associated with the array such as declaration, appending operation, insertion, looping over the array with for loop to even array deletion using unset command. Furthermore, it discusses 1 common pitfall in dealing with such a Bash array with elements of strings with spaces with effective solutions.

People Also Ask

How to empty an array in Bash of strings with spaces?

To empty an array in Bash of strings with spaces, use the unset command followed by the array’s name. The full syntax is unset array[@]. For example, to empty the array players=("leo messi" "zinedin zidan" "christiano ronaldo"), use the syntax unset players[@]. So, after printing the array length, the output will be 0.

Can I print the indices of the Bash array of elements containing spaces?

Yes, you can. Just use the syntax echo “${!array[@]}” to print only the indices of the array elements of string containing spaces. Here, in the expression ${!array[@]}, the exclamation mark ! denotes Bash to expand the array and fetch the indices only. Take the array food=("small pepsi" "medium burger" "large pizza") for instance. To print its indices, use the code echo "${!food[@]}" to get 0 1 2 as output (since the array is zero-indexed).

How do I access individual elements of an array containing elements with spaces in Bash?

To access individual elements of a Bash array containing elements as strings with spaces, you can use the syntax array[index]. This will access the elements located at index. To print the element on the screen, use the code echo “${array[index]}”. For instance, to access and print the 1st element “leo messi” of the array players=("leo messi" "zinedin zidan" "christiano ronaldo"), the syntax will be echo "${players[0]}".

How to append multiple elements to a Bash array of strings containing spaces?

To append multiple elements to a Bash array with elements containing spaces, use the general appending syntax array+=() and specify multiple elements one by one to the array separated be spaces. Remember to enclose each element with quotes. For example, to append 2 elements named “dinara safina” and “nikolai devidenko” to the array tennis=("roger federer" "rafael nadal"), use the syntax tennis+=("dinara safina" "nikolai devidenko").

Is it possible to populate an array in Bash with elements of string with spaces?

Yes. it is. Use the syntax array_name+=(“element with space”) to populate a bash array with elements containing spaces. This will add the element to the very end of the array. However, to populate the array with space-contained elements at any specified index, use the syntax array_name[index]=”element with space”.

Can I create an associative array in Bash containing elements of strings with space?

Absolutely. Use the command declare -A assoc_array to declare an associative array in Bash. Then initialize the array with key-value pairs where the values associated with each key will be strings containing space. For example, the code my_assoc_array["fruit"]=" komodo dragon" initializes a key “fruit” and associates it with the value “komodo dragon” which indeed is a string with space to the my_assoc_array.

Related Articles


<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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

2 thoughts on “Master Bash Array of Strings with Spaces [Complete Guide]”

  1. These “master” examples are so wrong, like #5 — appending element with spaces. The line:

    echo “array after appending: ${theatre[@]}”

    does not prove anything as the array is printed inline and you do not see the incorrect result. However, if you replace this with:

    for i in ${theatre[@]}; do
    echo $i
    done

    you will get:

    mike
    portnoy
    john
    petrucci
    jordan
    rudes
    john
    myung

    which obviously is not what was intended.

    Reply
    • Hello, thanks for your comment. As far as your query is concerned when you print the elements of the theatre array using the loop for i in ${theatre[@]}, each element goes through word splitting first during iteration. So, in this case, the elements with spaces are split with spaces.
      Now, to get the intended output using for loop, try using double quotes around the array expansion expression in this manner “${theatre[@]}”. This tells Bash to treat the entire element, with spaces, as a single unit.

      Hope this helps. Thank you.

      Reply

Leave a Comment