First of all, sorry for the heading. I'm not sure how to place my ambition in a few words. However, from a coding/scripting standpoint it should be pretty basic. Though, I somehow fail to achieve it :/

I have a bash script that awaits a user input (either via prompt or command-line argument). As there are only a few accepted answers I check them against an array. Let's call it 'packs' for now. Each accepted answer resembles an easy and human-readable alias for something else. That would be declared in the array in the second line.

declare -a packs=('low', 'mid', 'high')
declare -a packcontent=('1+1+2', '2+2+3', '3+3+4')


The point where I fail is to resolve the first array with the second one. How do I get the index of the user's input in order to pass it in a variable?

Example: If the user says 'low', it should notice 'low' is the first (zeroth) element of the first array. Therefore 'parameters' should be assigned the first (zeroth) element of the second array.


I'm not sure if I miss an intermediate step or bash can't substitute that, but I lack any idea how I achieve that.

Hope my explanation of the issue wasn't that messy.

Kind regards!

2 Answers 2


This looks like a job for bash associative arrays!

You can make arrays that take strings as indices. You might know them as "hashes" or "maps" from other languages. Consider the following:

$ declare -A packs
$ packs=( [low]='1+1+2' [mid]='2+2+3' [high]='3+3+4' )
$ parameters=${packs[low]}
$ echo $parameters
  • Thanks a lot! That makes the thing much better than expected.
    – Andreas
    Sep 10, 2019 at 10:05

wyrm's answer all well and good when using a recent release of bash, but for releases earlier than 4.0 (e.g. on macOS), you will have to rely on ordinary arrays.

Here's how you could do that:

packcontent=('1+1+2' '2+2+3' '3+3+4')
low=0 mid=1 high=2


The value in $parameters will be 2+2+3 since that's what's at index 1 in packcontent. The mid does not need to be prefixed with $ ("$mid") as the array index is evaluated in an arithmetic context.

For /bin/sh (no arrays), you could possibly get away with

set -- '1+1+2' '2+2+3' '3+3+4'
low=1 mid=2 high=3

eval "parameters=\$$mid"

That is, the list of possible parameters is kept in "$@" and the correct one is referenced with the help of one of $low, $mid or $high when assigning to parameters. The assignment is carried out with eval which will get the string parameters=$n to evaluate, with n replaced by the value of $mid (in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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