-1

I am comparing string in case statement as below : input variable can be D P KL ...

case $input in
      D|P|Q|L1|L2)
         val="Hello";;
      DD|DE|DF|CA)
          val="Hi" ;;
      MM|KL||TK|SZ)
         val="Bye" ;;
         echo $input

input variable not printing anything..

TKHN
  • 67
  • 2
  • 10
  • 3
    What is the value in `$input`? Also, the `case` statement is partial (not closed by `esac`), and you're not using `$val` anywhere. – Kusalananda Mar 29 '18 at 07:39
  • Should always be `case "$input"`. It seems to me that the esac is missing. Or shall `$input` be printed only in the last case? And why `$input` and not `$val`? Strange code... – Hauke Laging Mar 29 '18 at 07:42
  • 1
    @HaukeLaging Quoting `$input` in the `case` statement is good practice, but actually not necessary. https://unix.stackexchange.com/questions/68694/when-is-double-quoting-necessary (note, I always quote the expansion in `case` statements) – Kusalananda Mar 29 '18 at 07:51
  • yeah ..it was by mistake i didnot esac – TKHN Mar 29 '18 at 08:24

1 Answers1

8

There are two main issues in you script:

  1. The case statement is not closed by esac.
  2. The third pattern contains || which is a syntax error in most Bourne-like shells (use '' or "" or an expansion that resolves to an empty value to match on the empty string portably)

It's unclear what your script is actually doing, so I'm speculating a bit and wrote this:

#!/bin/sh

input="$1"

case "$input" in
      D|P|Q|L1|L2)
          val='Hello' ;;
      DD|DE|DF|CA)
          val='Hi' ;;
      MM|KL|""|TK|SZ)
          val='Bye' ;;
      *)
          echo 'error' >&2
          exit 1
esac

printf 'input was "%s", val is "%s"\n' "$input" "$val"

Testing it:

$ ./script.sh D
input was "D", val is "Hello"

$ ./script.sh MM
input was "MM", val is "Bye"

$ ./script.sh BOO
error
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Kusalananda
  • 320,670
  • 36
  • 633
  • 936