Bash For Loop Array: Iterate Through Array Values

How do I use bash for loop to iterate thought array values under UNIX / Linux operating systems?

The Bash provides one-dimensional array variables. Any variable may be used as an 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. Arrays are indexed using integers and are zero-based.

To declare an array in bash

Declare and an array called array and assign three values:

array=( one two three )

More examples:

files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
limits=( 10, 20, 26, 39, 48)

To print an array use:

printf "%s\n" "${array[@]}"
printf "%s\n" "${files[@]}"
printf "%s\n" "${limits[@]}"

To Iterate Through Array Values

Use for loop syntax as follows:

for i in "${arrayName[@]}"
do
   : 
   # do whatever on $i
done

$i will hold each item in an array. Here is a sample working script:

#!/bin/bash
# declare an array called array and define 3 vales
array=( one two three )
for i in "${array[@]}"
do
	echo $i
done
🐧 If you liked this page, please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
12 comments… add one
  • Peter Mar 6, 2009 @ 15:26

    Defining the array with double parentheses gave me an error. Using single parentheses did not and worked just fine. This tip mixes them, showing double parentheses at the top, but then using single parentheses in the for loop.

  • alok Aug 10, 2009 @ 7:55

    HI
    Want to know , how to create a Two dimension array in bash and print all in one go.
    eg like in one dimension array,
    echo ${array[@]}
    What for two dimension array ??

    Thanks in advance…

  • Ziad Nov 24, 2011 @ 18:32

    The double quotes are not necessary around ${array[@]}. This expression gets evaluated properly anyway.

    • Mark Jun 24, 2015 @ 13:59

      Not true, without the quotes you’ll have errors with elements with spaces. Try:

      $ arr=("a 1" "b" "c")
      
      $ for i in "${arr[@]}"; do echo $i; done
      a 1
      b
      c
      
      $ for i in ${arr[@]}; do echo $i; done
      a
      1
      b
      c
      
  • ushi Feb 25, 2012 @ 13:58

    ist there a nice way of doin this backwards? at the moment im writing something like this:

    for ((i=${#ARRAY[@]}; i > 0; i–)); do echo ${ARRAY[$i]}; done

    • Jorge Braz Apr 8, 2012 @ 14:55

      http://www.linuxjournal.com/content/bash-arrays

      ${arr[*]} # All of the items in the array
      ${!arr[*]} # All of the indexes in the array
      ${#arr[*]} # Number of items in the array
      ${#arr[0]} # Length of item zero

      for index in ${!array[*]}
      do
      printf “%4d: %s\n” $index ${array[$index]}
      done

  • koni Dec 11, 2012 @ 12:39

    I tried looping through a directory of approx 80 files. I looped trough them and placed them into an Array. Then I did a nested loop through the array to find duplicated (case insensitive) dir names.

    But this is just as slow as looping straight through the dirs using For x in ./*..

    Can someone with explain this?

  • Chris F.A. Johnson Dec 15, 2012 @ 18:22

    A loop is a loop. It is slow.

    It doesn’t matter whether you are looping through array elements or filenames, it’s the same thing.

    Assigning filenames to an array is fast if you can use pathname expansion:

    allfiles=( * )   ## 'shopt -s dotglob' if you want dot files included
    textfiles=( *.txt )
    

    Merely printing elements of an array doesn’t require a loop:

    printf "%s\n" "${textfiles[@]}"  ## yes, the double quotes ARE necessary
    
    • Anonymous May 26, 2016 @ 20:15

      Not true, you can actually still use single quotes.

      printf ‘%s\n’ ‘ ‘${textfiles[@]}’ ‘
      You just have to wrap the variable you’re putting in there in single quotes as well if you choose to use them.

  • daoluan Nov 24, 2014 @ 9:03

    good example.

  • bashnoob Dec 10, 2014 @ 0:50

    Thank you, I’m a bash noob and this helped me understand loops.

    Maybe you can help me with a challenge I am facing … I am trying to build a script to rsync certain files to a portable drive, and I want to use loop to iterate through file names, each on a new line in the script. The files are all in the same source directory, so I would just like to list the file names of the movies I want on a new line, and have the script copy each to the destination. For example:

    Movie Title 1.mkv
    Another Movie.mkv
    Some Other Title.mkv

    Is there a way I can define an array like that? How do I handle spaces in the file names?

  • Anirvan May 11, 2015 @ 11:15

    Hi bashnoob..
    Just use a for loop.
    May be try this.. but it depends on the version of the bash you are using..
    You can use folder1 and folder2 in a for loop to check the file system.. it would recognize the spaces and work accordingly with this.
    ls -lh “/$folder1/\”$folder11\””

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.