Home > Software engineering >  showing instructions for command line inputs in a bash script when run without inputs or wrong input
showing instructions for command line inputs in a bash script when run without inputs or wrong input

Time:06-09

I have created a bash script which takes 2 command line arguments. It works absolutely fine. I want to go a step further, and want to show the types of arguments it takes. i.e. if we run my_script.bash --help it should tell the desired arguments in its order.

my_script.bash is as follows

#!/bin/bash

X="$1" ## Name
Y="$2" ## address

 echo " Mr./Ms. $X lives in $Y ."

Since it takes two arguments name and address, I want to show these when this bash is executed without any inputs or number of inputs or using my_script.bash --help command.

ie executing ./my_script.bash or ./my_script.bash --help should show like below

$  ./my_script.bash

>>this script takes two arguments. please enter **Name** and **address**

Since these arguments are position specific so we cannot change the positions of Name and Address. It would be great if we could pass the arguments by defining --name --address.

$  ./my_script.bash --address Delhi --name Gupta
 >>  Mr./Ms. Gupta lives in Delhi .

Any help would be appreciated.

CodePudding user response:

A basic option parsing loop uses while and case, and looks like this:

print_help ()
{
    cat <<-EOF
    ${0##*/} - process name and address

    --name NAME        your name
    --address ADDRESS  your address
    --help             this help
    EOF
}

die ()
{
    echo "$@" >&2
    exit 1
}

while [[ $# -gt 0 ]]; do
    case $1 in
        --help)
            print_help
            exit
        ;;
        --name)
            shift || die "$1: requires input"
            name=$1
        ;;
        --address)
            shift || die "$1: requires input"
            address=$1
        ;;
        *)
            die "$1: invalid argument"
    esac
    shift
done

The order of options doesn't matter.

CodePudding user response:

You can test for [[ $1 == --help ]], but since your script has 2 required arguments, you could simply print the help whenever the number of arguments is not equal 2:

if (( $# != 2 ))
then
  echo You have to provide 2 arguments 1>&2
  exit 1
fi
  • Related