Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash case statement

Tags:

bash

shell

case

I'm trying to learn case as I was to write a fully functional script.

I'm starting off with the below

#!/bin/sh
case $@ in

    -h|--help)
            echo "You have selected Help"
            ;;
    -B|-b)
            echo "You have selected B"
            ;;
    -C|-c)
            echo "You have selected C"
            ;;
      *)
            echo "Valid Choices are A,B,C"
            exit 1
            ;;
esac

I want to use two of these options:

./getopts.sh -h -c

But i get this result Valid Choices are A,B,C

Please can you help out and let me know what I'm doing wrong?

I want to build a script that will do something if you enter one option but do multiple things if you enter multiple.

Also how would i parse $1 to this script as surley which ever option i enter first (-h) will be $1 ??

Thanks!

like image 261
bsmoo Avatar asked May 21 '13 15:05

bsmoo


People also ask

What is a case statement bash?

Last Updated 2022-09-06. A case statement is a conditional control structure that allows a selection to be made between several sets of program statements. It is a popular alternative to the if-then-else statement when you need to evaluate multiple different choices.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is $1 and $2 in bash?

$1 - The first argument sent to the script. $2 - The second argument sent to the script.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


2 Answers

Try this

#!/bin/sh

usage() {
    echo `basename $0`: ERROR: $* 1>&2
    echo usage: `basename $0` '[-a] [-b] [-c] 
        [file ...]' 1>&2
    exit 1
}


while :
do
    case "$1" in
    -a|-A) echo you picked A;;
    -b|-B) echo you picked B;;
    -c|-C) echo you picked C;;
    -*) usage "bad argument $1";;
    *) break;;
    esac
    shift
done
like image 93
Bruce Barnett Avatar answered Sep 29 '22 06:09

Bruce Barnett


Using getopt or getopts is the better solution. But to answer your immediate question, $@ is all of your arguments, so -h -c, which doesn't match any of the single-argument patterns in your case statement. You would still need to iterate over your arguments like so

for arg in "$@"; do
    case $arg in
       ....
    esac
done
like image 43
chepner Avatar answered Sep 29 '22 08:09

chepner