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..

4
  • 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
    Commented Mar 29, 2018 at 7: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... Commented Mar 29, 2018 at 7:42
  • 1
    @HaukeLaging Quoting $input in the case statement is good practice, but actually not necessary. unix.stackexchange.com/questions/68694/… (note, I always quote the expansion in case statements)
    – Kusalananda
    Commented Mar 29, 2018 at 7:51
  • yeah ..it was by mistake i didnot esac
    – TKHN
    Commented Mar 29, 2018 at 8:24

1 Answer 1

9

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
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.