3

I have created a script in order to use arguments while running that script. How to check if there were no arguments provided ? It must shows print help if no argument passes.

while test -n "$1"; do
         case "$1" in
            -help|-h)
            print_help
            exit $ST_UK
            ;;
        --version|-v)
            print_version $PROGNAME $VERSION
            exit $ST_UK
            ;;
        --activeusers|-a)
            opt_var=$2
            au
            shift;;
        --dailyusers|-d)
            opt_var1=$2
            dau
            shift;;
        *)
    echo "Unknown argument: $1"
        print_help
        exit $ST_UK
        ;;
    esac
    shift
done
blaCkninJa
  • 445
  • 2
  • 11
  • 22

1 Answers1

5

You can do it the same way you would for any POSIX shell, by testing the $# (number of arguments) magic variable:

if [ "$#" -eq 0 ]
then
    usage >&2
    exit 1
fi
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • Or, if no arguments, set the args to "--help" and use the while loop: `[[ $# -eq 0 ]] && set -- -h` – glenn jackman Aug 27 '18 at 11:11
  • @glenn - less good, because you want the error case to write to stderr and exit with a failure, but you want requested help to write to stdout and exit success. That's why I prefer a `usage` function for this. – Toby Speight Aug 27 '18 at 11:13