I want to write a script that loops through 15 strings (array possibly?) Is that possible?
Something like:
for databaseName in listOfNames
then
# D
listOfNames="db_one db_two db_three"
for databaseName in $listOfNames
do
echo $databaseName
done
or just
for databaseName in db_one db_two db_three
do
echo $databaseName
done
I loop through an array of my projects for a git pull
update:
#!/bin/sh
projects="
web
ios
android
"
for project in $projects do
cd $HOME/develop/$project && git pull
end
Surprised that nobody's posted this yet -- if you need the indices of the elements while you're looping through the array, you can do this:
arr=(foo bar baz)
for i in ${!arr[@]}
do
echo $i "${arr[i]}"
done
Output:
0 foo
1 bar
2 baz
I find this a lot more elegant than the "traditional" for-loop style (for (( i=0; i<${#arr[@]}; i++ ))
).
(${!arr[@]}
and $i
don't need to be quoted because they're just numbers; some would suggest quoting them anyway, but that's just personal preference.)
The declare array doesn't work for Korn shell. Use the below example for the Korn shell:
promote_sla_chk_lst="cdi xlob"
set -A promote_arry $promote_sla_chk_lst
for i in ${promote_arry[*]};
do
echo $i
done
Try this. It is working and tested.
for k in "${array[@]}"
do
echo $k
done
# For accessing with the echo command: echo ${array[0]}, ${array[1]}
Single line looping,
declare -a listOfNames=('db_a' 'db_b' 'db_c')
for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
you will get an output like this,
db_a
db_b
db_c