Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to set variable in case statement bash

I'm trying to set a variable based on a bunch of input conditions. Here's a small sample of the code:

#!/bin/bash
INSTANCE_SIZE=""
case "$1" in
   "micro")
     $INSTANCE_SIZE="t1.micro"
     ;;
   "small")
     $INSTANCE_SIZE="m1.small"

     ;;
esac
echo $INSTANCE_SIZE

When I run the script with the -ex switch and specify the proper argument:

+ case "$1" in
+ =m1.small
./provision: line 19: =m1.small: command not found
like image 279
upbeat.linux Avatar asked Jul 13 '11 08:07

upbeat.linux


People also ask

How do you set a variable value in bash?

The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

Are bash variables case sensitive?

Variables in Bash Scripts are untyped and declared on definition. Bash also supports some basic type declaration using the declare option, and bash variables are case sensitive.

Can you declare variables in bash?

A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.

How does case work in bash?

The case statement starts with the case keyword followed by the $variable and the in keyword. The statement ends with the case keyword backwards - esac . The script compares the input $variable against the patterns in each clause until it finds a match.


1 Answers

You need to remove the $ sign in the assignments - INSTANCE_SIZE="m1.small". With the dollar sign, $INSTANCE_SIZE gets substituted with its value and no assignment takes place - bash rather tries to execute the command that resulted from the interpolation.

like image 79
Blagovest Buyukliev Avatar answered Sep 18 '22 18:09

Blagovest Buyukliev