1

I have an array something like this, array=( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) I would like to list values “b, e, o, u, z” I tried using:

`echo ${array[1,4,14, 20, 25]}`

[This command doesn’t work] The output be: B E O U Z I’m not looking for

echo ${array[1] array[4] array [14]...}

What would be the perfect command to get this output?

1 Answer 1

1

I haven't found a way without eval:

#! /bin/bash
array=( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z )
x=(\${array[{1,4,14,20,25}]})
eval echo ${x[@]}
Sign up to request clarification or add additional context in comments.

5 Comments

sligthly better eval a=\( \"\${array[{1,4,14,20,25}]}\" \); echo "${a[@]}"
Did I stumble into a code golf challenge? What's wrong with plain old printf "%s " ${array[1]} ${array[4]} ${array[14]} ${array[20]} ${array[25]} ?
otherwise without eval x=(); for i in 1 4 14 20 25; do x+=( "${array[i]}" ); done; echo "${x[@]}"
@MikeHolt, the question is more about array slicing than golfing, and seems you missed the double quotes, and how do you handle an arbitrary list of indices
Easy enough to handle an arbitrary list of indices without using eval. I'm not in the "eval is evil, don't ever use it" camp (although the warnings about security are not without merit), but in this case it seems at best it saves you a slight amount of typing. Your own for loop example is plenty concise, and much clearer than the eval solution. Using eval just seems IMO like being needlessly clever. Not to mention the for loop will handle arbitrary lists of indices just fine.

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.