DRAFT: Work in progress. Publishing in a month or two.

Hello everyone! Here's part six of Bash One-Liners Explained. In this part I'll teach you all kinds of bash array tricks.

See part one for introduction. And parts two, three, four, five.

After I'm done with the series I'll release an ebook (similar to my ebooks on awk, sed, and perl), and also bash1line.txt (similar to my perl1line.txt).

Also see my other articles about working fast in bash:

Let's start.

Part 6: Working with arrays

1. Create an array with 5 elements

$ arr=(40 90 foo bar "$x")

Here we create an array called arr and assign it values 40, 90, foo, bar, and the contents of variable $x.

Here's another way to do it:

$ declare -a arr=(40 90 foo bar "$x")

And another:

$ arr[0]=40
$ arr[1]=90
$ arr[2]=foo
$ arr[3]=bar
$ arr[4]="$x"

Indexes don't have to be sequential, you can also do this:

$ arr[4]=40
$ arr[98]=90
$ arr[2525]=foo
$ arr[3333]=bar
$ arr[9999]="$x"

2. Print the 3rd element of an array

$ echo ${arr[2]}

Just like in C, bash arrays are 0-index based.

3. Create an array with numbers from 0 to 100

$ arr=({0..100})

Here we use brace expansion of form {x..y} that generates a range of integers from x to y.

Another way to do the same is to use seq command:

$ arr=(`seq 0 100`)

4. Create an array with entire alphabet a to z

$ arr=({a..z})

If you use letters in brace expansion, you get a range of letters.

5. Find the number of elements in array

$ arr=({a..z})
$ echo ${#arr[@]}
26

6. Print all array elements, one per line

$ arr=({a..z})
$ printf "%s\n" ${arr[@]}
a
b
c
...
z

This one-liner uses printf's hidden looping mechanism. Given a format and arguments, bash's printf will apply arguments to format as many times as possible.

This is how bash sees it:

$ printf "%s\n" a b c d e f g h i j k l m n o p q r s t u v w x y z

And printf formats each letter and prints it.

5. Create an associative array (hash) with 5 elements

$ declare -A arr=([key]=val [foo]=bar)

This creates an associative array arr with keys key and foo and values val and bar

7.

See you next time!

Let me know what you think and see you next time!