1

I found similar answers for bash, but not for sh so I'm asking.

I have a $STRING which contains something like "Jun01 Jun02 Jun03 Jun04". I would like to put this into an array such that ${ARRAY[0]} is "Jun01", ${ARRAY[1]} is "Jun02", etc.

How can I do this? Thank you.

3 Answers 3

2

You can't really handle arrays natively in the standard (Bourne) shell.

See here for more details.

The C shell ( 47.5 ) , awk ( 33.11 ) , the Korn shell, and some other UNIX command interpreters have built-in array support. The standard Bourne shell doesn't, though its command line is a sort-of array that you can store with the set ( 44.19 ) command - and get stored values through $1 , $2 , etc.

I would try and use bash (as you've identified) or a more fully featured scripting language such as Perl (no doubt others will suggest their favourites!)

Sign up to request clarification or add additional context in comments.

1 Comment

Ok I guess I'll go with bash.
1

sh does not have arrays, but the following hack is often adequate:

set $STRING
for x; do eval "ARRAY_$((i++))='$x'"; done

Now, (assuming i was unset or 0 to begin with), $ARRAY_0 has the value Jun01, $ARRAY_1 is Jun02, etc.

Comments

1

You can get away with the positional parameters: they're array-like.

set -- $STRING   # no quotes here
echo $1
echo $2
# etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.