I came 7 years later, I guess you don't need my answer anymore; However I struggled with sh
lack of arrays too. so I came up with some weird idea, Why won't I make a functions that will replace the arrays? I mean... I'm bad at describing in words, so let me show you, and tell me what you think.
Even if it won't be useful for you, I want to believe that someone will find it useful. After all, sh
is a bit tough...
Before we start,
#! /bin/sh
All the code will run on dash
(/ash
/sh
).
array_length () {
# The first argument of this function
# is the array itself, which is actually a string
# separated by a delimiter that we define in the
# second argument
array="${1}"
# The second field should be the separator.
# If it's not empty, set it as the local IFS.
if ! [ "${2}" = "" ]
then
local IFS=${2}
fi
# So far not bad,
# Let's count the elements in this array.
# We'll define the counter:
counter=0
# And now let's loop.
# Pay attention, do not quote the string,
# as it won't have the "array effect"
for element in ${array}
do
counter=$(( ${counter}+1 ))
done
# At the end of the function,
# Let's echo the amount.
echo "${counter}"
# Unset the variables (that's what I prefer,
# you, of course, don't have to)
unset array element counter
# And I guess we can exit normally
# unless you want to add a specific condition
# (for example, if the length is zero,
# the exit code will be bigger than 0).
# I prefer that it will be 'true' in all cases...
return 0
}
# Try it!
array_length 'Hello World!'
Now, You could use this idea for other ideas. For example, You want to find a value at a specific index:
array_value () {
# Just like before, only few things are different...
array="${1}"
# Now the second argument is the index
# to extract the value from
# (think of it as ${array[index]}
index="${2}"
# Now we loop through the array
# (I skipped the IFS thing on purpose,
# you can copy and include it if you desire)
# and once we match the index,
# we return the value
# Define a counter for each iteration
count=0
# Define the return status
status=1
for value in ${array}
do
if [ "${index}" -eq "${count}" ]
then
# It's a match
echo "#${index}: '${value}'"
# Set the return status to zero
status=0
# And stop the loop
break
fi
# Increase the counter
count=$(( ${count}+1 ))
done
# Of course you can add an return status
# I'll set it to a variable
return ${status}
}
# Try it!
world=$(array_value "Hello World!" 1)
echo ${world}
My code examples are released under GNU GPLv3 or later.
Tell me what you think about it, and if you like my ideas, feel free to use them!
If there's a better way to achieve these things with sh
, Feel free to correct me! I'd love to get a feedback.