Announcement

Collapse
No announcement yet.

Case statements in bash

Collapse
This topic is closed.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Case statements in bash

    I'm trying to write a bash script using a case statement. (I've already written it with "Russian-doll" nested if-then statements, and it runs, but I have more than two choices, so the if-then programming is kludgy.)

    I think that I'm getting hung up on how to express a test as a case alternative. First I'm giving the case statement its data file:

    case $starting_data in

    I want first to test whether the user included an argument on the command line invoking the script. With an if-then, that's easy:

    if [ $# -eq 0 ]
    then echo "Error"
    else [process a command list]

    But if, after the case line above, my next line reads

    [ $# -eq 0 ]) {Because this is the test for whether there were any arguments on the command line, right?}
    echo "Error"
    etc.

    then I get

    hw9case.sh: 7: hw9case.sh: Syntax error: "(" unexpected (expecting ")")

    and I'd be lying through my teeth if I pretended I could decipher that. I have a feeling I'm missing something really fundamental, but I've not been able to find anything online that has enlightened me (admittedly a hard job).

    Can someone set me straight? Thanks a lot.

    #2
    In bash case statements do a string pattern match. They're not a truth table like some languages, or an integer switch statement like others. You could
    Code:
    case $# in
       0)  echo Error whatever
            etc... ;;
    esac
    if you really wanted to. Old Bourne shell scripting lacked another fast way to test for a pattern match so you'd see case statements that were really if statements, but IMO it was a kludge, and shouldn't be used in modern bash scripting.
    Regards, John Little

    Comment

    Working...
    X