1

I'm trying to make my shell script similar to ordering at a fast food restaurant. However, I'm confused as to how to set arrays to determine the size of the drink the customer wishes to order. My sizes are as follows:

small=12oz
medium=16oz
large=20oz
xlarge =24oz

I have my shell script programmed to read the customers input for $size but I don't know how to translate the word "small" into an oz amount when customer declares their size. I as going to use the eval“$size="` option but what do I put so that it can vary? Will x be sufficient?

Thanks!

1
  • 3
    You could use variable indirection (retrieve the value of the variable whose name is specified as the value of $size), but a better practice would be to use associative arrays, which you will find explained here Commented Oct 29, 2018 at 16:51

1 Answer 1

4

Try an associative lookup.

$: declare -A drink=(
    [small]=12oz
    [medium]=16oz
    [large]=20oz
   )
$: choice=medium
$: echo "${drink[$choice]}"
16oz
$: drink[xlg]=32oz
$: choice=xlg
$: echo "${drink[$choice]}"
32oz

Watch the syntax, though, it's kind of a pain.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to declare size as an associative array first, or it defaults to being an indexed array. Notice in your example that ${size[$choice]} outputs 20oz, not 16oz as would be expected, because each of your assignments sets (and resets) size[0] as the strings are evaluated as variable names in the arithmetic contexts.
Thank you so much! I was having difficulty understanding the concepts of arrays. I understand how to set but I was confused on how to get it called back into my program. I'm just learning how to script and there's a lot of ways to get the job done!

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.