2

I got the following code. I would like to make cc dd ee ff as array [2]

    keyvariable="aa bb cc dd ee ff"
    while read -a line;
    do
       a=$(echo "${line[0]}")
       b=$(echo "${line[1]}")
       c=$(echo "${line[2]}")
    done <<< "$keyvariable" 
    echo "$a $b $c"

current output:

      aa bb cc   

I would like to have the following output, where aa is [0] bb is [1] and cc dd ee is [2]

      aa bb cc dd ee
2
  • what do u mean? im a bit dumb here. Commented Mar 12, 2015 at 17:25
  • 2
    Do you need c to be cc dd ee ff or just cc dd ee? Commented Mar 12, 2015 at 17:41

3 Answers 3

5

You don't need the while loop here at all.

You don't want to use read with the -a switch at all here. Instead you want:

read -r a b c <<< "$keyvariable"

In this case, read will split the (first line of the) expansion of the variable keyvariable on the spaces, but only for the first and second fields (these will go in variables a and b) and the remaining part will go in c. The -r switch is used in case you have backslashes in your string; without this, backslashes would be treated as an escape character.

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

1 Comment

@user1204671 did you echo "$a $b $c"?
0

gniourf_gniourf's answer is absolutely correct, however if you don't know how many fields you are going to have or need to select your "prefix" fields based on some other criteria then using an array and Substring Expansion (which is a bad name for this usage of it but that's what it is called) can let you do that.

$ keyvariable="aa bb cc dd ee ff"
$ read -a line <<<"$keyvariable"
$ a=${line[0]}
$ b=${line[1]}
$ c=${line[@]:2}
$ echo "$a"
aa
$ echo "$b"
bb
$ echo "$c"
cc dd ee ff

Also note the lack of $(echo ...) on the assignment lines. You don't need it.

2 Comments

This work as there would be many fields. One thing what does "${line[@]:3}" this do actually @ and 3 means....?
@user1204671 Check the link for Substring Expansion I just added. The ${parameter:offset} section.
-2

Just do

a=( $keyvariable )

and you have array a with your values, so your example would be

keyvariable="aa bb cc dd ee ff"
line=( $keyvariable ) # of course you can do it in the same line
a="${line[0]}"
b="${line[1]}"
n=$(( ${#line[@]} - 1))
unset line[$n]
echo "$a $b $c"

1 Comment

This doesn't really help the OP with his problem; moreover, this is a very bad line, as it is subject to pathname expansion.

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.