6

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!

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for a great explanation of the problem without spoon-feeding the final answer.
I had to look at the answer twice, but I understand, thank you very much! So by default $array maps to the first element and not the whole array. Strange syntax with the [@] for me though. Anyway, it works and I know it now ;-)
2

Write the beginning of your loop like this

for asteriskFile in "${asteriskFiles[@]}"

Comments

2

The Probem

The asteriskFiles variable holds an array. If you dereference it like a scalar, you only get the first element of the array.

The Solution

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.