Awesome Bash arrays

This post was published in 2013 and is kept here for reference. It may contain information that's outdated or inaccurate. All external links and references have been updated to point to archived versions on archive.org where possible.

Just some examples of how to do things with Bash arrays, and their analogous examples in Javascript.

Defining arrays

Javascript

var array = ["one","two","three","four","five"]

Bash

array=("one" "two" "three" "four" "five")

Looping through an array

Javascript

for (var i=0; i<array.length; i++) {
    console.log(array[i]);
}

Bash

for (( i=0; i<${#array[@]}; i++ ));
do
    echo ${array[$i]}
done

Getting the length of an array

Javascript

array.length; // output: 5

Bash

${#array[@]} # output: 5

Selecting a specific item in an array

Javascript

array[2]; // output: "three"

Bash

${array[2]} # output: "three"

Selecting a range of items in an array

It’s worth noting that in the Javascript example, we specify the start index and end index as parameters, but in the Bash example we specify the start index and length.

Javascript

array.slice(1,3); // output: ["two", "three"]

Bash

${array[@]:1:3} # output: two three four

Length of a single item in the array

Javascript

array[2].length; // output: 5

Bash

${#array[2]} # output: 5

Re-assign the value of an index in the array

Javascript

array[2] = "ten";

array; // output: ["one", "ten", "three", "four", "five"]

Bash

array[2]="ten"

${array} # output: one ten three four five

Add to end of an array

Javascript

array.push("nine");

array; // output: ["one", "two", "three", "four", "five", "nine"]

Bash

array=(${array[@]} "nine")

${array} # output: one two three four five nine

# bonus

array[${#array[@]}+1]="nine"

Concatenate two arrays

Javascript

var array2 = ["apple", "orange", "banana"];

var new_array = array.concat(array2);

new_array; // output: ["one", "two", "three", "four", "five", "apple", "orange", "banana"]

Bash

array2=("apple" "orange" "banana")

new_array=(${array[@]} ${array2[@]})

${new_array} # one two three four five apple orange banana

This post is also available in plain text

[Comments]

Want to comment? You can do so via Github.
Comments via Github are currently closed.

[Webmentions]

Want to reply? I've hooked up Webmentions, so give it a go!