So, I had a quick question about having multiple arguments being read into a bash script. In the following script, if I type "./myscript -h", it returns "Hippo.". However, if I type "./myscript -h -k", the script returns only "Hippo." I would like to know how to have the script print out both "Hippo." and "Kangaroo.". What is the easiest way to do this?

case "$*" in
*-h*)
echo "Hippo."
;;
*-k*)
echo "Kangaroo."
esac

Thanks in advance.

Dani AI

Generated

The case statement in the original post only runs the first matching pattern, so when both -h and -k are present it stops after printing the first match. Also, expanding all args into one string (with "$*") makes parsing brittle if an argument contains spaces. Two practical, robust ways to get both messages are shown below.

A POSIX-friendly solution is getopts, which iterates each short option (and handles combined flags like -hk):

#!/bin/sh
while getopts "hk" opt; do
  case "$opt" in
    h) echo "Hippo." ;;
    k) echo "Kangaroo." ;;
    *) printf 'Usage: %s [-h] [-k]\n' "$0" ; exit 2 ;;
  esac
done

A very simple alternative (easy to understand and good for fixed short flags) is to walk "$@" and test each element:

for arg in "$@"; do
  case "$arg" in
    -h) echo "Hippo." ;;
    -k) echo "Kangaroo." ;;
  esac
done

Building on 's hint: prefer getopts for option parsing (portable and robust). Use "$@" when iterating to preserve argument boundaries. If long options are needed, be cautious with external getopt implementations (they differ across platforms). These approaches ensure both "Hippo." and "Kangaroo." are printed when both flags are supplied.

Recommended Answers

All 2 Replies

Alright it solved my problem. Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.