Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this for-loop not process all elements of the array?

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!

like image 491
stefan.at.wpf Avatar asked Jul 09 '12 19:07

stefan.at.wpf


People also ask

Does for in loop work for array?

The for...in loop logs only enumerable properties of the iterable object. It doesn't log array elements 3 , 5 , 7 or "hello" because those are not properties — they are values.

Why do we use for loops with arrays?

- [Instructor] When you have values in an array, it is common to want to perform actions on each one of the items. You can use a for loop to iterate through all the items in the array and access each element individually.

How do you declare an array in a for loop?

You can declare (define) an array inside a loop, but you won't be able to use it anywhere outside the loop. You could also declare the array outside the loop and create it (eg. by calling new ...) inside the loop, in which case you would be able to use it anywhere as far as the scope the declaration is in goes.

What can you not do with an enhanced for loop with the array or collection?

4) You don't have access to array index in enhanced for loop, which means you cannot replace the element at giving the index, but for loop provide access to the index, hence allows you to replace any element in the array.


1 Answers

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.

like image 70
kojiro Avatar answered Nov 02 '22 23:11

kojiro