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

Chin Kk
  • 5
  • 2

2 Answers2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
Vrata Blazek
  • 464
  • 3
  • 12
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.

Community
  • 1
  • 1
wadkar
  • 960
  • 2
  • 15
  • 29