0

I'm working on a script that has an array of around 10 elements. All I have to do is that the script will accept user input of minimum 0 elements and maximum 10 elements (of the array) and it will execute whatever the corresponding array element says.


Example

Array -

array0=( [1]=echo "Foo" [2]=export CCACHE=true [3]=export FOO_FLAG=true [4]=unset BAR_FLAG )

Then the script will read inputs like -

read -a array0

And then something like -

for i in ${array0[@]}
do
   access each element as $i. . .
done

The output should look something like -

Type the elements - 1 4 2

Foo
*unset BAR_FLAG
*export CCACHE=true*

But i'm not able to do it unfortunately. There must be some mistake in the for/do loop.

If anybody can help...

1 Answer 1

1
#!/bin/bash

array0=('echo Foo' 'export CCACHE=true' 'export FOO_FLAG=true' 'unset BAR_FLAG')

echo -n "Enter the elements: "

read -e line

for index in $line;do
        ${array0[index]}
done

Usage: script.sh

First index of an array is 0.

2
  • I can use read here too right?
    – Chinmay
    Sep 18, 2015 at 12:07
  • Modified the script to wait for user input.
    – jijinp
    Sep 18, 2015 at 12:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .