Reputation: 17624
Given the following script:
#!/bin/bash
asteriskFiles=("sip.conf" "extensions.conf")
for asteriskFile in $asteriskFiles
do
# backup current configuration file
cp somepath/${asteriskFile} test/
echo "test"
done
This gives me the output "test" only once, so the loop runs only once instead of two times (two entries in asteriskFiles array). What am I doing wrong? Thanks for any hint!
Upvotes: 6
Views: 2916
Reputation: 84343
The asteriskFiles variable holds an array. If you dereference it like a scalar, you only get the first element of the array.
You want to use the correct shell parameter expansion to access all the subscript elements. For example:
$ echo "${asteriskFiles[@]}"
sip.conf extensions.conf
The @ subscript (when correctly quoted) will expand to the properly-tokenized elements of your array, which your for-loop will then be able to iterate over.
Upvotes: 2
Reputation: 950
Write the beginning of your loop like this
for asteriskFile in "${asteriskFiles[@]}"
Upvotes: 2
Reputation: 77089
An illustration:
$ asteriskFiles=("sip.conf" "extensions.conf")
$ echo $asteriskFiles # is equivalent to echo ${asteriskFiles[0]}
sip.conf
$ echo "${asteriskFiles[@]}"
sip.conf extensions.conf
Note that the quotes are important. echo ${asteriskFiles[@]}
might seem to work, but bash would wordsplit on whitespace if any of your files had whitespace in them.
Upvotes: 11