I want to write a script that loops through 15 strings (array possibly?) Is that possible?
Something like:
for databaseName in listOfNames
then
# D
In addition to anubhava's correct answer: If basic syntax for loop is:
for var in "${arr[@]}" ;do ...$var... ;done
there is a special case in bash:
When running a script or a function, arguments passed at command lines will be assigned to $@
array variable, you can access by $1
, $2
, $3
, and so on.
This can be populated (for test) by
set -- arg1 arg2 arg3 ...
A loop over this array could be written simply:
for item ;do
echo "This is item: $item."
done
Note that the reserved work in
is not present and no array name too!
Sample:
set -- arg1 arg2 arg3 ...
for item ;do
echo "This is item: $item."
done
This is item: arg1.
This is item: arg2.
This is item: arg3.
This is item: ....
Note that this is same than
for item in "$@";do
echo "This is item: $item."
done
#!/bin/bash
for item ;do
printf "Doing something with '%s'.\n" "$item"
done
Save this in a script myscript.sh
, chmod +x myscript.sh
, then
./myscript.sh arg1 arg2 arg3 ...
Doing something with 'arg1'.
Doing something with 'arg2'.
Doing something with 'arg3'.
Doing something with '...'.
myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
Then
myfunc item1 tiem2 time3
Working about 'item1'.
Working about 'tiem2'.
Working about 'time3'.