Nik
Nik

Reputation: 1

Bash Scripting- Switches

#!/bin/bash
while getopts "p:" opt; do
case ${opt} in
 p )#print the argument value
echo "I like $OPTARG programming"
;;
 \? )

What if i want to print an error if I don't give '-p'

Upvotes: 0

Views: 357

Answers (1)

crdrisko
crdrisko

Reputation: 484

When I have a required option in my shell scripts, I use parameter expansion, specifically: ${variable:?message}, which will print message if $variable is empty or unset. You can introduce this into your code like this:

#!/bin/bash
while getopts "p:" opt
do
  case ${opt} in
    p) valueToPrint=$OPTARG ;;
  esac
done

# print the argument value
printf "I like %s programming\n" ${valueToPrint:?A -p option is required.}

You have effectively three scenarios that could arise with this program:

  • Without the parameter:

    $ bash test.sh
    test.sh: line 10: valueToPrint: A -p option is required.
    
  • With the option flag but no parameter:

    $ bash test.sh -p
    test.sh: option requires an argument -- p
    test.sh: line 10: valueToPrint: A -p option is required.
    
  • With both the option flag and the parameter:

    $ bash test.sh -p bash
    I like bash programming
    

Upvotes: 2

Related Questions