Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show help text if no arguments are passed

Tags:

linux

bash

I've been using getopts recently and I've set everything up. I've got a problem though. I want it to work so that if someone doesn't enter an argument on the command line, they get the help text, e.g.:

$ ./script
$ help: xyz - argument must be used.

Here's what I have at the moment.

#!/bin/bash

function helptext {
    # ...
}

function mitlicense {
    # ...
}


while getopts "hl" opt; do
  case $opt in
    h) helptext >&2
      exit 1
    ;;
    l) mitlicense >&2
      exit 0
    ;;
    \?) echo "Invalid option: -$OPTARG" >&2
      exit 1
    ;;
    :) echo "Option -$OPTARG requires an argument." >&2
      exit 1
    ;;
    *) helptext >&2
      exit 1
    ;;
  esac
done
like image 563
user2298964 Avatar asked Apr 20 '13 12:04

user2298964


People also ask

How do you read no of arguments passed to the script?

You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments". $# is read-only. When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

When receiving command line arguments in a script $0 is?

Command-line arguments are read in a positional manner, from position $1, $2, .. $n . The pattern $ followed by an integer is a reserved combination to represent the command-line arguments. $0 denotes the name of the script.

Can you pass in an argument to a bash script?

2. Argument List. Arguments can be passed to a bash script during the time of its execution, as a list, separated by space following the script filename. This comes in handy when a script has to perform different functions depending on the values of the input.


1 Answers

Validate user input using an if test such as below.

The -z option of test returns true if the length of the string which follows -z is zero.

 if [ -z "$1" ]
 then
  helptext
  exit 1
 fi
like image 126
suspectus Avatar answered Sep 20 '22 05:09

suspectus