#!/bin/bash
: '
VERSION 1
Loop through array using variable name
'
loopArray () {
echo "First argument passed: "$1;
local arrayname=$1
# check for named arguments [-a || --array]
for i in "$@" ; do
case $i in
-a=*|--array=*)
a="${i#*=}"
local arrayname=$a
;;
esac
done
# turn arrayname into local array
local tmp=$arrayname[@]
local array=( "${!tmp}" )
# loop through values
for value in "${array[@]}" ; do
echo $value
done
}
: '
define external list
'
LIST=(
'abc'
'123'
'The quick brown fox jumps over the lazy dog'
)
: '
Test
'
result=$(loopArray LIST);
echo $result
loopArray LIST
loopArray -a=LIST
loopArray --array=LIST
: '
First argument passed: LIST abc 123 The quick brown fox jumps over the lazy dog
First argument passed: LIST
abc
123
The quick brown fox jumps over the lazy dog
First argument passed: -a=LIST
abc
123
The quick brown fox jumps over the lazy dog
First argument passed: --array=LIST
abc
123
The quick brown fox jumps over the lazy dog
'
: '
VERSION 2
Function accepts array values as first param
'
loopArray () {
echo "First argument passed: "$1;
# convert the first argument
# from scalar to new array
# NOTE: whitespace space acts as the delimiter
_array=($1)
# check for named arguments [-a || --array]
for i in "$@" ; do
case $i in
-a=*|--array=*)
a="${i#*=}"
_array=($a)
;;
esac
done
# loop through values
for value in "${_array[@]}" ; do
echo $value
done
}
: '
define external list
'
list=(
'a'
'b'
'c'
'two words' # this method won't work with spaces
)
: '
Test
Must pass the array as scalar values -- no spaces
'
result=$(loopArray "${list[*]}");
echo $result
loopArray "${list[*]}"
loopArray -a="${list[*]}"
loopArray --array="${list[*]}"
: '
First argument passed: a b c two words a b c two words
First argument passed: a b c two words
a
b
c
two
words
First argument passed: -a=a b c two words
a
b
c
two
words
First argument passed: --array=a b c two words
a
b
c
two
words
'
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.