Home > Blockchain >  In Bash, how to branch on various conditions on a single-character variable? [duplicate]
In Bash, how to branch on various conditions on a single-character variable? [duplicate]

Time:10-04

Consider this Python code:

var = '1'
if var in '123':
    print('in 123')
elif var == 'x':
    print('is x')
elif var == 'y':
    print('is y')

How would one write this cleanly in Bash?

CodePudding user response:

Bash’s, and indeed POSIX’s, equivalent would be case.

Your Python example would then translate to:

var='1'
case "${var}"
in
  [123])
    printf 'in 123\n'
    ;;
  x)
    printf 'is x\n'
    ;;
  y)
    printf 'is y\n'
    ;;
esac

You can use POSIX pattern matching (a.k.a. globs) in the patterns, e.g. *foo*) printf 'contains foo\n'.

And a default ’case’ (the default in other languages’ switch constructs) would be *).

  • Related