Bash String Array
Bash String Array
In Bash scripting, creating and working with a string array is useful for various tasks that require managing textual data in arrays.
Syntax
array=("value1" "value2" "value3")
The basic syntax involves using parentheses to initialize an array with string elements separated by spaces and enclosed in double quotes.
Example Bash String Array
Let's look at some examples of how to create and work with a string array in Bash:
1. Create a String Array
This script initializes an array with string elements and prints the array.
#!/bin/bash
array=("apple" "banana" "cherry")
echo "String array: ${array[@]}"
In this script, the array variable array
is initialized with the strings 'apple', 'banana', and 'cherry'. The script then prints the array.
2. Access Elements in a String Array
This script initializes a string array and prints each element by accessing them using their indices.
#!/bin/bash
array=("dog" "cat" "mouse")
echo "First element: ${array[0]}"
echo "Second element: ${array[1]}"
echo "Third element: ${array[2]}"
In this script, the array variable array
is initialized with the strings 'dog', 'cat', and 'mouse'. The script then prints each element by accessing them using their indices.
3. Iterate Over a String Array
This script initializes a string array and iterates over each element to print them.
#!/bin/bash
array=("red" "green" "blue")
for element in "${array[@]}"; do
echo "$element"
done
In this script, the array variable array
is initialized with the strings 'red', 'green', and 'blue'. The for
loop iterates over each element in the array and prints it.
4. Modify Elements in a String Array
This script initializes a string array, modifies an element, and prints the modified array.
#!/bin/bash
array=("one" "two" "three")
array[1]="TWO"
echo "Modified array: ${array[@]}"
In this script, the array variable array
is initialized with the strings 'one', 'two', and 'three'. The second element of the array is modified to 'TWO'. The script then prints the modified array.
5. Concatenate String Arrays
This script initializes two string arrays, concatenates them, and prints the combined array.
#!/bin/bash
array1=("hello" "world")
array2=("foo" "bar")
combined_array=(${array1[@]} ${array2[@]})
echo "Combined array: ${combined_array[@]}"
In this script, the array variables array1
and array2
are initialized with strings. The elements of both arrays are concatenated into a new array, combined_array
. The script then prints the combined array.
Conclusion
Creating and working with a string array in Bash is a fundamental task for managing textual data in arrays in shell scripting. Understanding how to create, access, iterate over, modify, and concatenate string arrays can help you manage and manipulate textual data effectively in your scripts.