sh + how to use array in sh script in order to print all values in array
Little late, but I don't see the ideal sh
answer here so I'll chime in. If you don't need subscripting, then sh
effectively does support arrays. It just supports them as space separated strings. You can print the entire contents of them, "push" to them, or iterate through them just fine.
Here's a bit of sample code:
NAMES=""
NAMES="${NAMES} MYNAME"
NAMES="${NAMES} YOURNAME"
NAMES="${NAMES} THEIRNAME"
echo 'One at a time...'
for NAME in ${NAMES}; do
echo ${NAME};
done
echo 'All together now!'
echo ${NAMES}
Which outputs:
One at a time...
MYNAME
YOURNAME
THEIRNAME
All together now!
MYNAME YOURNAME THEIRNAME
Now, I said it doesn't support sub-scripting, but with a little bit of cut
magic and using the space as a proper delimiter, you can absolutely emulate that. If we add this to the bottom of our above example:
echo 'Get the second one'
echo ${NAMES} | cut -d' ' -f2
echo 'Add one more...'
NAMES="${NAMES} TOM"
echo 'Grab the third one'
echo ${NAMES} | cut -d' ' -f3
And run it, we get:
Get the second one
YOURNAME
Add one more...
Grab the third one
THEIRNAME
Which is what we'd expect!
However, a string with a space in it can cause an issue and will completely break the sub-scripting.
So, really the better statement is: Arrays are non-obvious in sh
and handling arrays of strings with spaces is hard. If you don't need to do that (e.g., an array of host names you want to deploy to), then sh
is still a fine tool for the job.
sh
does not support array, and your code does not create an array. It created three variable arr1
, arr2
, arr3
.
To initialize an array element in a ksh
-like shell, you must use syntax array[index]=value
. To get all element in array, use ${array[*]}
or ${array[@]}
.
Try:
n=1
eval arr[$n]=a
n=2
eval arr[$n]=b
n=3
eval arr[$n]=c
n=1
eval echo \${arr[$n]}
n=2
eval echo \${arr[$n]}
n=3
eval echo \${arr[$n]}
n='*'
eval echo \${arr[$n]}