Scrutinizer's read
method works, but you can also use set
to set the positional parameters ($1
, $2
etc.) which is about as close to an array you can get in dash
. If you do this cleverly (using local
) it can be quite useful.
Heres a little function, that splits $STRING
on $SEPARATOR
and then evals $CODE
for each token. The variable $TOKEN
is set when the eval is called, so you can use that. With a modification you could give it the token position as well. (And if you do anything advanced in your $CODE
you might want to to reset $IFS
as well.)
# Usage: foreach_token SEPARATOR STRING CODE
foreach_token() {
local IFS="$1" STRING="$2" CODE="$3" TOKEN # get args
set -- $STRING # split $STRING on $IFS
for TOKEN; do # foreach $@
eval "$CODE"
done
}
Call the function like this:
foreach_token "|" "firstfield|secondfield|thirdfield" 'echo "$TOKEN"'