5

I am trying to parse incoming options in my bash script, and save the values in variables. This is my code:

#!/bin/bash 

while getopts "H:w:c" flag
do 
#  echo $flag $OPTIND $OPTARG
    case $flag in
    H) host = "$OPTARG"
    ;;
    w) warning = "$OPTARG"
    ;;
    c) critical = "$OPTARG"
    ;;
    esac
done

However, the statements inside 'case' must be command-line commands, so I can't make the wanted assignment. What is the right way to do this?

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
hizki
  • 709
  • 1
  • 8
  • 19

3 Answers3

13

Remove the spaces around the = operators:

case "$flag" in
  H) host="$OPTARG" ;;
  w) warning="$OPTARG" ;;
  c) critical="$OPTARG" ;;
esac
Adam Liss
  • 47,594
  • 12
  • 108
  • 150
0

I took a slightly different approach when creating a script to practice if/then/else and case statements. BTW, if you install cowsay;

    sudo apt-get install cowsay

and fortune;

    sudo apt-get install fortune

you can use this script as is and then play around with it to get used to making assignments in case statements or using if/then/else statements.

    #!/bin/bash
    echo "Choose a character from the following list:"
    echo
    echo "1) Beavis"
    echo "2) Cow Hitting a Bong"
    echo "3) Calvin"
    echo "4) Daemon"
    echo "5) Dragon and Cow"
    echo "6) Ghostbusters"
    echo "7) Ren"
    echo "8) Stimpy"
    echo "9) Sodomized Sheep"
    echo "0) Mech and Cow"
    #
    echo
    read character
    echo
    #
    case "$character" in
      "1") file="beavis.zen.cow" ;;
      "2") file="bong.cow" ;;
      "3") file="calvin.cow" ;;
      "4") file="daemon.cow" ;;
      "5") file="dragon-and-cow.cow" ;;
      "6") file="ghostbusters.cow" ;;
      "7") file="ren.cow" ;;
      "8") file="stimpy.cow" ;;
      "9") file="sodomized-sheep.cow" ;;
      "0") file="mech-and-cow.cow" ;;
      *) clear; ./cowsay.sh;
    esac
      #
    #echo "var 'file' == $file"
    echo "What would you like your character to say?"
    echo "Alternatively, if you want your character to"
    echo "read you your fortune, type 'fortune'."
    read input_string
    #
    if [ $input_string = fortune ] ; then
      clear; $input_string | cowsay -f /usr/share/cowsay/cows/$file
    else
      clear; cowsay -f /usr/share/cowsay/cows/$file $input_string
    fi
    ~   
Bus42
  • 130
  • 6
0

You also need to change the optstring - The c option needs to be followed by a colon if you want to collect its argument:

while getopts "H:w:c:" flag
l0b0
  • 55,365
  • 30
  • 138
  • 223