• 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 assign array element

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

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.

Linux Guides, Tips and Tutorials | LinuxScrew

Home » Linux » Shell » Bash Array

Bash Array

Array Variables in Bash, How to Use, With Examples

We’ve covered using variables in Bash previously  – this article will explain Bash  array  variables and provide some example usage.

What is an Array

An array is a type of variable that can hold multiple values. It’s a list of values you can loop through and perform operations on each individual value.

For example, you might want to perform an action on a list of files. By storing that list as an array, you can loop through the file names in it and perform the action on each one.

Arrays are indexed, with the position of each item in the array being represented by a number starting at  0 .

Bash arrays do not require that array elements be indexed  contiguously – or adjacent without gaps – you can have values at array positions 0, 3, 17 with no values in between, for example.

You can find out more about Bash arrays at the  Linux Documentation Project .

Creating Bash Arrays

Bash arrays can contain any type of bash variable – paths, strings, numbers – even other arrays.

Why You Should Wrap File Paths in Strings in Your Shell Scripts

There are several methods for declaring arrays, outlined below.

Indirect Declaration

Arrays can be declared indirectly by assigning the array element’s value – the array will be created along with the array element with the given value.

For example:

The array  peopleArray will be created automatically (indirectly) when a value in the array is assigned – in this case, the value “Tom” is assigned to index 3 in the newly created  peopleArray .

Direct Declaration

The declare command can also be used to define an array :

This would create an empty array called  peopleArray .

Creating via Compound Assignment

This is the method you’ll probably use most. It creates an array with the values already assigned.

This assigns the value of the array to the variable name. The array values are contained in  ()  (standard brackets) and separated by spaces. Values containing spaces should be quoted.

Assigning Values to an Array

Adding a new value to the end of an array.

To add a value to an array, assign the value with no index specified:

Replacing Value in an Array

To replace a value, overwrite the value at the current value’s index.

For example, if you have an array with a value at index 7 which you wish to replace:

Deleting Value in an Array

Delete a value from an array by using the  unset  command and specifying the array index:

…will delete the second value in the array  peopleArray .

Accessing Array Values

To access the value in an array, you must use curly braces – otherwise, Bash will not interpret the brackets containing the array index correctly:

…will output:

Whereas if the last line were:

Looping Arrays

The most common thing you’ll do with arrays is loop through them to perform operations on each element. We’re way ahead of things and have already covered this article .

  • Variables in Bash/Shell Scripts and How To Use Them…
  • Bash Scripts Set Environmental Variables with EXPORT [HowTo]
  • Assign Variables, Global Variables and Scopes in JavaScript…
  • Array.shift() to Remove First Item from JavaScript Array…

Photo of author

Leave a Comment Cancel reply

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

Privacy Overview

  • 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

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
  • Privacy Policy

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

LinuxSimply

Home > Bash Scripting Tutorial > Bash Array > Elements of Bash Array

Elements of Bash Array

Md Masrur Ul Alam

Working with the elements of an array in Bash is the foremost step in efficient data management using Scripts within arrays. So, this tutorial will discuss the ins and outs of the elements of an array in Bash, from accessing and modifying to even removing the elements along with Bash script development.

What Are the Elements of Array in Bash?

Array elements in Bash refer to the individual data values or items stored within the array and accessible through numerical indices in indexed arrays or user-defined keys in the associative arrays. Bash arrays can store data irrespective of type. It can store elements of only string type like the following array:

hello=("world" "universe" "multiverse")

On the other hand, it stores both strings and numbers in the same array like the following:

exceptional=(10 "hello" 3.14)

NOTE : Even when assigning numerical values, the Bash array stores them as strings by default. For example, the array numbers=(10 20 30 40 50) stores the elements “10” “20” “30” “40” “50” as strings and not any numeric data type. Bash doesn’t practice rigidity in terms of data type so it treats elements as strings within an array.

Thus, for any mathematical calculation, using explicit type conversion tools like “$((…))” or “expr” is recommended.

Access Array Elements

Accessing the array is the foremost step in working with the elements of an array in Bash. The length expressions ${array_name[@]} and ${array_name[*]} access the elements of array_name and print them on the screen using the echo command in a single line.

Here’s how to access an entire indexed array called ABC in Bash employing the syntax echo ${ABC[@]} and echo ${ABC[*]} :

In the above code, the expressions ${ABC[@]} and ${ABC[*]} expand the array to access the items and print them to the screen using the echo command.

accessing and printing elements

Access an Associative Array in Bash

To access the elements of an associative array in bash, use the same syntaxes echo ${assoc_array[@]} and echo ${assoc_array[*]} . However, it only prints the values associated with the keys. Here’s an example:

Here, the ${my_associative[@]} expression accesses an associative array named my_associative with 3 key-value pairs. Finally, the command echo ${my_associative[@]} prints only the array values on the screen.

access bash associative array elements

NOTE : You can also access specific elements of the indexed array and associative array in Bash. To learn more, read the articles: Index Array in Bash and Bash Associative Arrays

Access the Last Array Element Using a Negative Index

Bash arrays can elegantly use the negative index to access the last element. Instead of counting from the start, negative indices count backward from the end of the array. For instance, -1 refers to the last element, -2 refers to the second last item, and so on. Thus, using the index assignment syntax with “-1”, ${your_array[-1]} , returns the last element and the echo command prints the value on the terminal.

To access the last element of an indexed array, you can use the syntax, echo ${your_array[-1]} , like the following example:

Here, the expression ${shoes[-1]} accesses the last element nike of the array shoes using the negative index ‘-1’ and the echo "last item:${shoes[-1]}" command prints the value nike on the screen.

access last element using negative index

Loop Through the Elements of Array in Bash

Using Bash loop-based methods are general approach to iterate over an array. To loop through the Bash array elements using for loop with the syntax for elem in ${array[@]} , see the example below:

First, the complete looping expression for elements in ${fruit[@]} iterates through the fruit array until it covers the entire array length (which is 3) and prints the items into the terminal iteratively on new lines using echo $item .

loop through the bash array elements

Add Array Elements

Adding a new element in an array is very simple in Bash. Use the =+ operator with the syntax array_name+=(element to add) . By default, it adds an element to the end of the specified array.

Here’s an example to add an array element CSE in an indexed array named dept using syntax dept+=(CSE) :

adding new elements

NOTE : To add multiple elements to an array, use array+=(item1 item2 ..ItemN) . For instance, to add MME and ECE to the above array, the syntax is: dept+=(MME ECE)

Add Array Elements Using Index Assignment

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 . Here’s how:

adding elements of array using index assignment

Modify Array Elements in Bash

To modify an array element is to replace the extant value with a new value in the same position. The syntax  array[index]= new_value modifies the array element by updating with the new_value at the specified index . Here’s an example:

Here, the hello[2]=williamson expression updates the content of index 2 (3rd position) from kohli to williamson. The echo "after modification:${hello[@]}" command prints the array with the updated contents.

modify the array values

Remove Array Elements

To delete an array element, use the unset command followed by the index value like the format: unset array_name[index]

Here’s an example to show how to remove an element from an indexed array:

In the script, the unset juice[1] command removes the 2nd element banana . After that, the echo command prints the array twice to show that the unset command has removed the array element.

removing array element using unset command

NOTE : To learn how to add, remove, and modify elements to a Bash associative array, read the article: “Bash Associative Arrays”

Extract a Particular Element from an Array in Bash

You can extract a specific part of an array element in Bash of string type. Take the array sen=(‘howdy parallel universe monster!’ ‘storm is coming’ ‘world cup ends’) for instance. If you want to extract words from the 1st element (‘howdy parallel universe monster!’) , you can use modifiers in variable expansion like the below:

Here, in the provided code:

${sen[0]##* } : Prints the last word of the first array element by removing everything before the last space.

${sen[0]%% *} : Prints the first word of the first array element by removing everything after the first space.

${sen[0]#* } : Extracts the words after the first space, and `${tmp%% *}` prints the first word from this extracted section.

${sen[0]#* * } : Extracts the words after the second space, and `${tmp2%% *}` prints the first word from this extracted section.

extract particular array element

In closing, this tutorial has discussed the intricacies of elements of arrays in Bash from accessing elements to manipulating them dynamically showing several hands-on illustrations. I hope this article empowers your scriptwriting capabilities in terms of efficient data handling and fosters elegant solution-building by mastering array fundamentals. Happy Scripting!

Frequently Asked Question

How to create a bash array.

To create a Bash array:

  • Use the syntax declare -a <array_name> to create an empty array.
  • To create an array with initialized elements use: array_name=(element1 element2.. elementN) .

How do you delete all the elements of an array in Bash?

Use the unset command followed by the array name to delete all the elements of an array in Bash. For example, to delete elements of an array named numbers , use: unset numbers .

You can recreate the same array using array_name=() or declare -a array_name . For instance, to delete all elements of the array numbers use the syntax: declare -a numbers=() or numbers=()

It is possible to access the Bash associative array elements using the negative index?

No , since Bash associative arrays don’t support negative indices to access elements. Rather, it uses a unique set of keys that are not maintained in any sequential order. A negative index is only an attribute available to the regular indexed arrays in Bash.

How to get the number of elements in the Bash array?

The number of elements of a Bash array is the length of that array. To get the length of an array in Bash, use the expression ${#your_array[@]) with the echo command. For instance, if you have an array nums=(1 2 3) which you intend to get the length of, then use the syntax echo ${#nums[@]} . It will return 3 as the output on the terminal.

What’s the syntax to access a specific element in a Bash array?

To access any specific element in a Bash array, use the syntax ${your_array[index]} , where index is the position of the element you want to access. For instance, the syntax echo ${number[0]} prints the first element of the array number .

How do I loop through all the elements in a Bash array?

To loop through all the elements in a Bash array use the Bash for loop syntax for elem in ${array[@]} to iterate over the entire array. For example, to iterate over the array number=(1 2 3 4) , the syntax is:

What is a Bash array?

A Bash array is a data structure that stores values in an indexed way. Unlike arrays in other programming languages, bash array can store different types of elements. For example, you can use Bash arrays to store both strings and numbers.

Related Articles

  • 3 Ways to Iterate an Array in Bash
  • Check If Bash Array Contains [Letters, Numbers, or Values]

<< Go Back to Bash Array | Bash Scripting Tutorial

Md Masrur Ul Alam

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.

Bash Array – How to Declare an Array of Strings in a Bash Script

Bash scripts give you a convenient way to automate command line tasks.

With Bash, you can do many of the same things you would do in other scripting or programming languages. You can create and use variables, execute loops, use conditional logic, and store data in arrays.

While the functionality may be very familiar, the syntax of Bash can be tricky. In this article, you will learn how to declare arrays and then how to use them in your code.

How to Declare an Array in Bash

Declaring an array in Bash is easy, but pay attention to the syntax. If you are used to programming in other languages, the code might look familiar, but there are subtle differences that are easy to miss.

To declare your array, follow these steps:

  • Give your array a name
  • Follow that variable name with an equal sign. The equal sign should not have any spaces around it
  • Enclose the array in parentheses (not brackets like in JavaScript)
  • Type your strings using quotes, but with no commas between them

Your array declaration will look something like this:

That's it! It's that simple.

How to Access an Array in Bash

There are a couple different ways to loop through your array. You can either loop through the elements themselves, or loop through the indices.

How to Loop Through Array Elements

To loop through the array elements, your code will need to look something like this:

To break that down: this is somewhat like using forEach in JavaScript. For each string (str) in the array (myArray), print that string.

The output of this loop looks like this:

Note : The @ symbol in the square brackets indicates that you are looping through all of the elements in the array. If you were to leave that out and just write for str in ${myArray} , only the first string in the array would be printed.

How to Loop Through Array Indices

Alternatively, you can loop through the indices of the array. This is like a for loop in JavaScript, and is useful for when you want to be able to access the index of each element.

To use this method, your code will need to look something like the following:

The output will look like this:

Note : The exclamation mark at the beginning of the myArray variable indicates that you are accessing the indices of the array and not the elements themselves. This can be confusing if you are used to the exclamation mark indicating negation, so pay careful attention to that.

Another note : Bash does not typically require curly braces for variables, but it does for arrays. So you will notice that when you reference an array, you do so with the syntax ${myArray} , but when you reference a string or number, you simply use a dollar sign: $i .

Bash scripts are useful for creating automated command line behavior, and arrays are a great tool that you can use to store multiple pieces of data.

Declaring and using them is not hard, but it is different from other languages, so pay close attention to avoid making mistakes.

Veronica is a librarian by trade with a longtime computer programming habit that she is currently working on turning into a career. She enjoys reading, cats, and programming in React.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

How to Declare Arrays in Bash: A Shell Scripting Guide

Graphic illustration of declaring an array in Bash with array brackets and index markers emphasizing data structure organization

Are you finding it challenging to handle arrays in Bash? You’re not alone. Many developers find themselves puzzled when it comes to declaring and manipulating arrays in Bash, but we’re here to help.

Think of Bash arrays as a toolbox – each slot holding a different tool. These tools can be anything from strings to integers, giving you a versatile and handy tool for various tasks.

This guide will walk you through the process of declaring arrays in Bash , from the basics to more advanced techniques. We’ll cover everything from the simple declaration of arrays, accessing and manipulating array elements, to more complex uses like multi-dimensional and associative arrays.

So, let’s dive in and start mastering Bash arrays!

TL;DR: How Do I Declare an Array in Bash?

In Bash, you declare an array using the following syntax: array_name=(item1 item2 item3) . This creates an array named ‘array_name’ with three items.

Here’s a simple example:

In this example, we’ve declared an array named ‘array_name’ with three items: ‘Bash’, ‘Python’, and ‘JavaScript’. We then use the echo command to print each item. The numbers in the square brackets are the indices of the array items. In Bash, arrays are zero-indexed, meaning the first item is at index 0.

This is just a basic way to declare an array in Bash, but there’s much more to learn about accessing and manipulating arrays. Continue reading for more detailed examples and advanced usage scenarios.

Table of Contents

Bash Arrays: Declaration and Manipulation

Expanding bash array knowledge: advanced usage, harnessing external tools for data handling, common pitfalls and best practices with bash arrays, bash arrays: the fundamentals, the bigger picture: arrays in larger bash scripts, wrapping up: declaring arrays in bash.

Let’s get started with the basics of declaring, accessing, and manipulating arrays in Bash. We’ll cover each step in detail and provide a simple code example for better understanding.

Declaring an Array

In Bash, we declare an array using the parentheses () syntax. Here’s how:

In this example, we’ve declared an array named ‘programming_languages’ with four items.

Accessing Array Elements

To access an element in an array, we use the array name followed by the index of the element in square brackets [] :

In this example, we’ve printed the first item of the ‘programming_languages’ array. Remember, Bash arrays are zero-indexed, so the first item is at index 0.

Manipulating Arrays

You can also add, modify, or remove elements from an array. Here’s how you can add an item to the array:

In this example, we’ve added ‘Java’ to the ‘programming_languages’ array and then printed all items.

Arrays in Bash are incredibly versatile, but they come with potential pitfalls. For instance, Bash doesn’t support multi-dimensional arrays natively, and arrays are zero-indexed, which can lead to off-by-one errors if you’re not careful. But don’t worry, with practice, you’ll get the hang of it!

While Bash is limited to one-dimensional indexed arrays, we can simulate multi-dimensional arrays with a bit of creativity. Also, Bash supports associative arrays, which are arrays that use named keys instead of numerical indexes. Let’s take a closer look.

Simulating Multi-Dimensional Arrays

To simulate a multi-dimensional array in Bash, we can use a single-dimensional array and calculate the equivalent index. Here’s an example:

In this example, we’ve declared a single-dimensional array ‘matrix’ and accessed it as if it were a 3×3 matrix. We calculated the index using the formula index = columns * row + column .

Associative Arrays

Associative arrays are a type of array that uses named keys rather than numerical indexes. Here’s how you declare and use an associative array:

In this example, we’ve declared an associative array ’employee’ and assigned values to it using named keys. We then accessed the values using these keys.

Array Operations

Bash provides several operations to manipulate arrays, such as adding and removing elements, and finding the length of an array. Here’s an example of how to find the length of an array:

In this example, we’ve found the length of the ‘programming_languages’ array using ${#array_name[@]} .

These advanced techniques can greatly extend the utility of arrays in Bash, providing you with more flexibility and power in your scripting.

While arrays are a powerful tool in Bash, they’re not the only way to handle collections of data. Sometimes, using external tools such as awk or sed can be more suitable, especially when dealing with large data sets or complex string manipulation.

Leveraging Awk for Data Manipulation

Awk is a powerful text processing language that can be used to manipulate data in Bash. It can be used to split strings into arrays based on a delimiter. Here’s an example:

In this example, we’ve used awk to split a string into an array based on the colon ‘:’ delimiter. We then printed all items in the array.

Using Sed for String Manipulation

Sed is another text processing tool that can be used in Bash. It’s particularly useful for find and replace operations on strings. Here’s an example of how you can use sed to manipulate a string and store the results in an array:

In this example, we’ve used sed to replace hyphens ‘-‘ with spaces in a string. We then converted the manipulated string into an array and printed all items.

While these external tools provide additional flexibility, they also come with their own drawbacks. For instance, they can be slower than native Bash operations, especially with large data sets. Moreover, they add external dependencies to your scripts, which can lead to portability issues.

The decision to use arrays or external tools depends on your specific use case. If you’re dealing with simple data collections, arrays might be the way to go. However, if you need to perform complex string manipulation or deal with large data sets, external tools like awk or sed might be more suitable.

Working with arrays in Bash can sometimes lead to unexpected results. Let’s discuss some common errors and how to avoid them. We’ll cover off-by-one errors, uninitialized array elements, and how to handle spaces in array elements.

Off-By-One Errors

A common mistake when working with arrays in Bash is off-by-one errors. This happens because arrays in Bash are zero-indexed, which means the first item is at index 0, not 1. Here’s an example of an off-by-one error:

In this example, we tried to access the fifth item of the ‘programming_languages’ array, but there are only four items. The echo command didn’t print anything because there’s no fifth item. Always remember that the index of the last item is one less than the length of the array.

Uninitialized Array Elements

Another common mistake is trying to access uninitialized array elements. In Bash, uninitialized array elements don’t cause an error; they simply return an empty string. Here’s an example:

In this example, we tried to access the eleventh item of the ‘programming_languages’ array, but it’s uninitialized. The echo command didn’t print anything because the eleventh item doesn’t exist.

Handling Spaces in Array Elements

Spaces in array elements can cause unexpected behavior if not handled properly. To avoid issues, always quote your array elements and expansions. Here’s an example:

In this example, we’ve declared an array with six items, two of which (‘C++’ and ‘C#’) contain spaces. We then printed all items correctly by quoting the array expansion.

Remember, arrays in Bash are a powerful tool, but they come with potential pitfalls. Always remember to consider the zero-indexing, initialize your array elements, and handle spaces properly.

To truly master Bash arrays, it’s essential to understand how they’re implemented in Bash and how they differ from arrays in other programming languages.

Bash Array Implementation

In Bash, arrays are implemented as ordered maps, with keys being represented as integers. This means that arrays in Bash can have gaps in their indices. Here’s an example:

In this example, we’ve declared an array ‘sparse_array’ with gaps in its indices. We then printed all items, which are ordered by their indices.

Bash vs. Other Languages

Bash arrays are different from arrays in other programming languages in several ways. First, they’re one-dimensional, meaning they can only hold a list of items. However, you can simulate multi-dimensional arrays using associative arrays or calculated indices.

Second, Bash arrays are zero-indexed, which means the first item is at index 0. This is similar to languages like C, Java, and JavaScript, but different from languages like Lua and MATLAB, which are one-indexed.

Third, Bash arrays can have gaps in their indices, which is not common in other languages. This can be a powerful feature, but it can also lead to unexpected behavior if not handled properly.

Lastly, Bash supports associative arrays, which are arrays that use named keys instead of numerical indexes. This is similar to dictionaries in Python or objects in JavaScript, and it provides a lot of flexibility in handling collections of data.

Understanding these fundamentals will help you use Bash arrays more effectively and avoid common pitfalls.

Arrays are an integral part of any Bash script, especially those that are more complex and larger in scale. They allow you to manage and manipulate collections of data efficiently and effectively.

Arrays in Larger Bash Projects

In larger Bash projects, arrays can be used to hold data that needs to be processed or manipulated. For example, you might have a script that processes a list of files. You could use an array to hold the file names, and then loop over the array to process each file in turn.

Here’s an example:

In this example, we’ve declared an array of file names and then used a for loop to print each file name. This is a simple demonstration, but you can imagine how this could be expanded to include more complex operations on each file.

Related Topics: String Manipulation and File I/O

While arrays are powerful, they are just one tool in the Bash toolkit. To become a proficient Bash scripter, you’ll need to master several other topics, including string manipulation and file input/output (I/O).

String manipulation in Bash involves operations like splitting strings, replacing substrings, and concatenating strings. These operations often go hand-in-hand with array manipulation, as you might need to split a string into an array, or join an array into a string.

File I/O in Bash involves reading from and writing to files. This is crucial for scripts that need to process data stored in files. You might need to read a file into an array, or write an array to a file.

Further Resources for Bash Array Mastery

If you’re interested in diving deeper into Bash arrays, here are some resources that you might find helpful:

  • GNU Bash Manual : This is the official manual for Bash, and it includes a detailed section on arrays.
  • Advanced Bash-Scripting Guide : This guide covers advanced topics in Bash scripting, including arrays.
  • Introduction to Bash Arrays : This article from Opensource.com serves as an introduction to Bash arrays.

In this comprehensive guide, we’ve explored the ins and outs of declaring arrays in Bash, a fundamental aspect of Bash scripting that enables you to manage and manipulate collections of data efficiently.

We began with the basics, learning how to declare, access, and manipulate arrays in Bash. We then delved into more advanced topics, such as simulating multi-dimensional arrays, working with associative arrays, and leveraging external tools like awk and sed for data handling.

Along the way, we tackled common challenges you might encounter when using arrays in Bash, such as off-by-one errors, uninitialized array elements, and handling spaces in array elements. We provided solutions and best practices to help you avoid these pitfalls and work effectively with arrays.

We also compared Bash arrays with other methods of data handling in Bash, giving you a sense of the broader landscape of tools available to you. Here’s a quick comparison of these methods:

Whether you’re a beginner just starting out with Bash or a seasoned scripter looking to brush up on your array handling skills, we hope this guide has provided you with a deeper understanding of Bash arrays and their capabilities.

The ability to declare and manipulate arrays in Bash is a powerful tool in your scripting toolkit. Now, you’re well equipped to handle collections of data in Bash effectively and efficiently. 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

java_projects_construction_big_java_cup

IMAGES

  1. How to Use Arrays in Bash Shell Scripts

    bash assign array element

  2. Bash Associative Array Explained With Examples In Linux

    bash assign array element

  3. Full Guide to Bash Arrays

    bash assign array element

  4. How to use arrays in Bash

    bash assign array element

  5. BASH tutorials

    bash assign array element

  6. How to use arrays in Bash

    bash assign array element

VIDEO

  1. Array-Backed Properties

  2. php 04 19 arrays stack function

  3. Bash Script Array #15

  4. Arrays

  5. Assign array elements from user input

  6. 30 JavaScript ES6

COMMENTS

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

    How can I assign a value to an array in Bash? Ask Question Asked 11 years, 8 months ago Modified 2 years, 3 months ago Viewed 42k times 12 I am trying to read a list of values from a text file, hello.txt, and store them in an array.

  2. How to Use Arrays in Bash Shell Scripts

    First, use the naïve approach of using five different variables: #!/bin/bash file1="f1.txt" file2="f2.txt" file3="f3.txt" file4="f4.txt" file5="f5.txt" touch $file1 touch $file2 touch $file3 touch $file4 touch $file5

  3. 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 ...

  4. How to use bash array in a shell script

    In this tutorial you will learn how to: Create bash array Print values from bash array Obtain bash array size Add and delete bash array elements How to use bash array in a shell script Software Requirements and Conventions Used

  5. Introduction to Bash Array

    Array elements : Baeldung is cool. Here, we use the @ symbol as the index to specify all the members of our array. We also surround the array variable with the ${} construct.This triggers Bash parameter expansion.. We'll see some interesting possibilities with this a bit later. Alternatively, we can also use the ∗ symbol as an index to obtain the same output:

  6. 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.

  7. Arrays (Bash Reference Manual)

    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.

  8. Array Variables in Bash, How to Use, With Examples

    Arrays can be declared indirectly by assigning the array element's value - the array will be created along with the array element with the given value. ARRAYNAME [INDEX]=VALUE For example: #!/bin/bash peopleArray [3]="Tom"

  9. Bash Tutorial => Array Assignments

    Create an array with new elements: array= ('first element' 'second element' 'third element') Subscript Assignment Create an array with explicit element indices: array= ( [3]='fourth element' [4]='fifth element') Assignment by index array [0]='first element' array [1]='second element' Assignment by name (associative array) 4.0

  10. How to Declare and Access Associative Array in Bash

    Use the Bash declare keyword to create an empty associative array in Bash. For example: declare -A example_array. The -A tag tells the declare command to create an associative array if supported. The declaration does not print an output. To populate the array, enter new values one by one: example_array ["key1"]="value1".

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

    Assign Element of Array to Variable 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 happens if I miss my French night train (intercités de nuit) if my connecting Eurostar is delayed or cancelled?

  12. Elements of Bash Array

    What Are the Elements of Array in Bash? Array elements in Bash refer to the individual data values or items stored within the array and accessible through numerical indices in indexed arrays or user-defined keys in the associative arrays. Bash arrays can store data irrespective of type.

  13. Bash Array

    To declare your array, follow these steps: Give your array a name. Follow that variable name with an equal sign. The equal sign should not have any spaces around it. Enclose the array in parentheses (not brackets like in JavaScript) Type your strings using quotes, but with no commas between them. Your array declaration will look something like ...

  14. shell

    1 You can use this script: server_farm= ("10.0.10.1" "10.0.10.2") for ( (i=0, j=1; i< $ {#server_farm [@]}; i++, j++)); do declare "srv$j"="$ {server_farm [$i]}" done Test:

  15. How to Declare Arrays in Bash: A Shell Scripting Guide

    To truly master Bash arrays, it's essential to understand how they're implemented in Bash and how they differ from arrays in other programming languages. Bash Array Implementation. In Bash, arrays are implemented as ordered maps, with keys being represented as integers. This means that arrays in Bash can have gaps in their indices.

  16. Use For Loop With Array in Bash

    Using an index in an array; Let's start with the first one. Use for loop with array for every element . In this method, you can use a variable that will be used to print every element of the array. You can use any name for the variable to store the value of the element for the ongoing iteration. Here, I went with the item as a variable.

  17. bash

    What's the easiest way to assign them to a bash array? If I simply assign them to a variable they become a space-separated string. arrays bash command-substitution Share Improve this question Follow edited Oct 12, 2015 at 16:31 ks1322 34.6k 14 111 165 asked Feb 26, 2012 at 0:25 ceiling cat 5,601 9 39 53 See this question - beerbajay

  18. Bash

    Bash - How to assign list to array member Ask Question Asked 1 year, 11 months ago Modified 4 months ago Viewed 2k times 4 In bash, I've an array with values: declare -A my_array my_array ['key1']='value1' my_array ['key2']='value2' echo "-----my_array-----" echo key1: $ {my_array ['key1']} echo key2: $ {my_array ['key2']} what works well:

  19. Extracting the last string from each array element

    You were looping on the array indices instead of values, and then trying to operate on the array instead of the value. Just loop on each value and operate on that instead: