How to show help text if no arguments passed

I recently used getopts and I got it all worked out. I have a problem. I want it to work so that if someone does not enter an argument on the command line, they get help text, for example:

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

Here is 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 
+7
source share
3 answers

Confirm user input with the if test, for example, below.

The -z test option returns true if the length of the line that follows -z is zero.

  if [ -z "$1" ] then helptext exit 1 fi 
+9
source

Try using this in a script:

 #!/bin/bash [[ $@ ]] || { helptext; exit 1; } # --- the rest of the script --- 

The line of code is a boolean shortened version.

 if [[ $@ ]]; then true else helptext exit 1 fi 

$@ - all script arguments

 [[ $var ]] 

is short for

 [[ -n $var ]] 

See http://mywiki.wooledge.org/BashGuide/TestsAndConditionals

+6
source

Gil Kenot's answer works great and is very brief; if you are looking for solutions that express intent, you can try them that are based on parameter counting, $# :

 [[ $# -gt 0 ]] || { helptext; exit 1; } 

Alternative using arithmetic expressions:

 (( $# > 0 )) || { helptext; exit 1; } 

Finally, a shorthand that relies on 0 evaluating to false, and any nonzero number is true:

 (( $# )) || { helptext; exit 1; } 

William Pursell offers another option that is both descriptive and POSIX compatible:

 test $# -gt 0 || { helptext; exit 1; } 

test / [ ... ] is a POSIX / built-in utility, while a similar condition is [[ ... ]] bash specific (as is (( ... )) ).
However, as a rule, bash [[ ... ]] offers more features and has fewer surprises than test / [...] .

+5
source

All Articles