bash shell script declaring/creating arrays
Posted by Quinn McHenry in Bourne shell scripting
The use of array variable structures can be invaluable. This recipe describes several methods for declaring arrays in bash scripts.
The following are methods for declaring arrays:
names=( Jennifer Tonya Anna Sadie )
This creates an array called names with four elements (Jennifer, Tonya, Anna, and Sadie).
names=( "John Smith" "Jane Doe" )
This creates two array elements, each containing a space.
colors[0] = red
colors[3] = green
colors[4] = blue
This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2).
filearray=( `cat filename | tr '\n' ' '`)
This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly.
names=( "${names[@]}" "Molly" )
This example adds another element to an existing array names.
If anyone has other techniques for creating or adding to arrays, add a comment to this recipe and share the wealth!
About Quinn McHenry
View more articles by Quinn McHenry
The Conversation
Follow the reactions below and share your own thoughts.





December 08, 2008 at 10:09 am, Barun said:
Wow!!! The trick for initializing an array from a file is superb!
December 16, 2008 at 1:01 pm, Punit said:
Here is another method of adding elements in the array.. It works best with korn shell
set -A array_example 1 2 3 4 5
i=0
echo ${array_example[$i]}
January 22, 2009 at 12:19 pm, secoif said:
One way to merge two arrays:
#existing array
existing=(item1, item2, item3);
#items to merge (including an item requiring correct quoting)
merge=(item4 item5 “${item6}*”);
count=${#existing[@]};
num_new_items=${#merge[@]};
# this loop appends items to the end of the array
for (( i=0;i
January 29, 2009 at 2:00 pm, Erik J said:
Reading a line, while preseriving whitespaces seems har dto do from a file
You can do it this way:
cat $file | while read line; do
echo “$line”;
done
April 28, 2009 at 11:35 am, bob.experience said:
Well done man! Thanks for the tip!
April 13, 2009 at 9:49 am, Manav said:
Good one
November 11, 2009 at 11:21 pm, asd said:
asdasdasd
July 12, 2010 at 7:11 am, Aparnacomp said:
to convert a decimal number into its equivalent binary number…..using shell script:
created by APARNA……….
program
echo ” program to convert a decimal number into its equivalent binary number…….”
echo -e “enter a decimal number….”
read no
d=$no
echo “____________________________________________________________”
r=0
b=0
if test $d -eq 0
then
echo “Binary of 0 is 0…”
else
if test $d -eq 1
then
echo “Binary of 1 is 1…”
else
i=0
echo “d=$d”
while [ $d -ne 1 ]
do
r=`expr $d % 2`
d=`expr $d / 2`
echo ” r=$r”
echo “d=$d”
#add one by one element in an array………
a=( “${a[@]}” “$r” )
i=$i+1
done
a=( “${a[@]}” “$d” )
fi
fi
echo “___________________________________________________________”
len=${#a[*]}
echo “equivalent binary number of $no is…..”
j=-1
l=`expr $len – 1`
while [ $l -gt $j ]; do
printf “%2d” ${a[$l]}
let l–
done
printf “n”
echo ” GOOD BYE……….”
July 28, 2010 at 4:30 am, Ll said:
did u create it.. wow….
August 03, 2010 at 7:13 pm, Ayesha said:
How can I insert elements in an array from another text file?? I want to read numbers from another text file and insert them in an array??
August 18, 2010 at 2:46 pm, Bill Hernandez said:
As I was digging through my notes I found this…
——————————————————
NOTES : Sample code for [ jot ] command…
——————————————————
# +———+———+———+———+———+———+———+———+———+
RANDOM NUMBERS – print three random numbers between [1 - 500]
[2007.06.08](06:26AM) -> [bhernandez] ~
$ operation=-r ; reps=3 ; begin=1 ; end=500 ; jot $operation $reps $begin $end
15
438
164
# +———+———+———+———+———+———+———+———+———+
SEQUENCE OF NUMBERS
jot 21 -1 1.00 # prints 21 evenly spaced numbers increasing from -1 to 1.
jot 20 5 # prints 20 evenly spaced numbers starting at 5
my_seq=`jot 20 1` # prints 20 evenly spaced numbers starting at 1
echo ${my_seq}
# +———+———+———+———+———+———+———+———+———+
# ROUTINE FROM bh_dir_samples – Example using {sed, wc, jot, and a for loop}
# FOR MORE EXAMPLES SEE –> bh_dir_samples
# +———+———+———+———+———+———+———+———+———+
echo
echo “( 19 ) BASH – Example using {sed, wc, jot, and a for loop}”
my_path=”/tmp/state/city/farm/barn/tractor/keys/red/small”
my_str=`echo “$my_path” | sed ‘s/// /g’`
my_word_count=`echo $my_str | wc -w` ;
how_many_levels_back=2
max_count=`expr $my_word_count – $how_many_levels_back`
my_seq=`jot $max_count 1` # prints 20 evenly spaced numbers starting at 1
n=1
for arg in $my_str ;
do
if [ $n -gt 0 ]
then
if [ $n -le $max_count ]
then
# echo -n “$n/$arg”
# echo -n “/$arg”
my_result=”${my_result}/${arg}”
fi
fi
let “n++”
done
echo “( a ) –> $my_path = $my_path”
echo “( b ) –> $how_many_levels_back = $how_many_levels_back”
echo “( c ) –> $max_count = $max_count”
echo “( d ) –> $my_seq = `echo $my_seq`” # ( d ) This one shows up on one line
echo “( e ) –> $my_seq = ${my_seq}” # ( e ) This shows up on separate lines
echo “( f ) –> $my_seq = `echo $my_seq | sed ‘s/n/ /g’`” # ( f ) This one shows up on one line
echo “( g ) –> $my_result = $my_result”
exit
# +———+———+———+———+———+———+———+———+———+
# RESULTS
# +———+———+———+———+———+———+———+———+———+
( 19 ) BASH – Example using {sed, wc, jot, and a for loop}
( a ) –> $my_path = /tmp/state/city/farm/barn/tractor/keys/red/small
( b ) –> $how_many_levels_back = 2
( c ) –> $max_count = 7
( d ) –> $my_seq = 1 2 3 4 5 6 7
( e ) –> $my_seq = 1
2
3
4
5
6
7
( f ) –> $my_seq = 1 2 3 4 5 6 7
( g ) –> $my_result = /tmp/state/city/farm/barn/tractor/keys
# +———+———+———+———+———+———+———+———+———+
[2007.05.08](04:40PM) -> [bhernandez] ~
$
# +———+———+———+———+———+———+———+———+———+
September 14, 2010 at 8:18 am, Varun Avashia said:
#Initialize commands
init command
echo “Total packages found: ” $(rpm -qa | grep -c “some string”)
#Search for packages and remove them one by one
for package in $(rpm -qa | grep “some string”);
do
echo “Removing ” $package
rpm -fe $package
done
#Cleanup
Clean up commands
echo “Remaining packages: ” $(rpm -qa | grep -c “some string”)
September 22, 2010 at 7:19 am, Matt Duffy said:
Hi, just found this site and it’s been really helpful so far. I have a problem with assigning the output of a find command into an array. The find command works fine on it’s own:
find “$path” ( -type d -o -type f ) -name ‘[.]*’ -print0
where $path is a string with a file system path. This finds all files or directories in a subtree with names that begin with a dot (.svn, .DS_Store, etc). Currently, the output is piped to xargs to delete the files it finds. It uses the -print0 to account for space characters in $path.
What I would like to do is have the output redirected into an array where each array element is a string path value for a file/directory with a dot name. The problem I am having is that there are many files the subtree that have spaces in their name and when the find command output is redirected to the array the space characters in the string cause it to be split into more than one array element.
For example, a string like:
web/Cappuccino/iTunes Layout/Frameworks/AppKit/Resources/.DS_Store
will be split at iTunesLayout to create array elements
array[n] = web/Cappuccino/iTunes
array[n+1] = Layout/Frameworks/AppKit/Resources/.DS_Store
I have tried a number of different syntaxes all with the same result. I feel like it’s just a simple error in my variable quoting or something, but I am stuck. I think it should look something like this (but this is wrong):
array=( `find “$path” ( -type f -or -type d ) -name ‘[.]*’ -print0 | xargs -0 -n 1` )
Any suggestions? I am really stuck on this.
Cheers
July 01, 2011 at 5:58 pm, Bf Hayati said:
thats great but can any one know how to use array in loop like ,or know how to change number from decimle into binary plzzzzzzzzzzzzz
April 07, 2012 at 10:40 pm, Souradeep Das said:
// The simplest shell script for dec-bin conversion
enjoy frnds \m/
echo “Enter any decimal no:”
read num
rem=”"
bno=” ”
while [ $num -gt 0 ]
do
rem=`expr $num % 2 `
bno=$bno$rem
num=`expr $num / 2 `
done
final=” ”
l=`echo $bno|wc -c`
l=`expr $l – 1`
i=$l
while [ $i -gt 0 ]
do
rev=`echo $bno | cut -c $l`
final=$final$rev
l=`expr $l – 1`
i=$(( $i – 1 ))
done
echo “Equivalent Binary no:” $final