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!
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.
- [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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With