2

I'm currently looking at an existing script that have something like this:

variable='val1 val2 val3 val4'

Is this another way of setting an array? If not, what is it?

2

This is a variable with a string assigned to it.

variable='val1 val2 val3 val4'

You can tell it's a string when we output it using echo:

$ echo $variable
val1 val2 val3 val4

Example of an array

To define that series of elements as an array you could do the following:

$ variable=(val1 val2 val3 val4)

When you echo out variables that are defined as arrays, you'll get just the first element returned, like so:

$ echo $variable
val1

To see specific elements in the array, you can provide an index:

$ echo ${variable[0]}
val1
$ echo ${variable[2]}
val3

Or all of them:

$ echo ${variable[@]}
val1 val2 val3 val4
  • @casey Ah, good catch, deleted. – Chris Down Jan 29 '14 at 2:22
  • @ChrisDown - sorry I thought you realized that and were just giving another position if it were Bash. – slm Jan 29 '14 at 2:23
1

That is not an array. To create that as an array you would use

set -A variable val1 val2 val3 val4

which would assign val1 to variable[0], and so on.

What you have there appears to just be values joined by spaces () into a single string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.