Justin Siev
Justin Siev

Reputation: 23

BASH shell script searching and displaying a pattern

I am trying to create a BASH shell script in which I prompt the user to enter an animal, and return "The $animal has (number I set in case statement) legs"

I am using a case statement for this. My current statement is below:

#!/bin/bash

echo -n "Enter an animal: "
read animal

case $animal in
spider|octopus) echo "The $animal has 8 legs";;
horse|dog) echo "The $animal has 4 legs";;
kangaroo|person) echo "The $animal has 2 legs";;
cat|cow) echo "The $ animal has 4 legs";;
*) echo "The $animal has an unknown number of legs"
esac

For a cat or cow, I need to be able to echo "The (xyz) (cat or cow) has 4 legs" I am thinking of using a grep somewhere but don't know if that is the best option for this. Can anyone help out?

Thanks!

Upvotes: 1

Views: 159

Answers (2)

Justin Siev
Justin Siev

Reputation: 23

It seems that adding *cat|*cow) instead of cat|cow) worked without any need for grep. Thanks

Upvotes: 0

Cyrus
Cyrus

Reputation: 88583

With chepner's suggestion:

#!/bin/bash

echo -n "Enter an animal: "
read -r animal

case $animal in
  spider|octopus)       n=8;;
  horse|dog)            n=4;;
  kangaroo|person)      n=2;;
  cat|cow)              n=4;;
  *)                    n="an unknown number of"
esac

echo "The $animal has $n legs"

Upvotes: 1

Related Questions