0

i have to task to write a bash script which can let user to choose which array element(s) to display.

for example, the array have these element

ARRAY=(zero one two three four five six)

i want the script to be able to print out the element after user enter the array index

let say the user entered(in one line) : 1 2 6 5

then the output will be : one two six five

the index entered can be single(input: 0 output: zero) or multiple(such as above) and the output will be correspond to the index(es) entered

any help is much appreciated.

thanks

2 Answers 2

1
ARRAY=(zero one two three four five six)
for i in $@; do
    echo -n ${ARRAY[$i]}
done
echo

Then call this script like this:

script.sh 1 2 6 5

it will print:

one two six five
Sign up to request clarification or add additional context in comments.

Comments

0

You would want to use associative arrays for a generic solution, i.e. assuming your keys aren't just integers:

# syntax for declaring an associative array
declare -A myArray
# to quickly assign key value store
myArray=([1]=one [2]=two [3]=three)
# or to assign them one by one
myArray[4]='four'
# you can use strings as key values
myArray[five]=5
# Using them is straightforward
echo ${myArray[3]} # three
# Assuming input in $@
for i in 1 2 3 4 five; do
    echo -n ${myArray[$i]}
done
# one two three four 5

Also, make sure you're using Bash4 (version 3 doesn't support it). See this answer and comment for more details.

2 Comments

There's nothing in the question that requires an associative array.
Agreed, I edited to the answer to reflect a generic solution

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.