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

share|improve this question
up vote 1 down vote accepted
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
share|improve this answer
  • fast and simple, many thanks – Chin Kk Sep 18 '15 at 13:24

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.

share|improve this answer
  • There's nothing in the question that requires an associative array. – chepner Sep 17 '15 at 15:46
  • Agreed, I edited to the answer to reflect a generic solution – Sudhi Sep 17 '15 at 15:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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