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
2
  • 4
    Use: (( $# )) || print_help the the top of your script Commented Aug 27, 2018 at 10:59
  • Great! It's working Commented Aug 27, 2018 at 11:09

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Or, if no arguments, set the args to "--help" and use the while loop: [[ $# -eq 0 ]] && set -- -h
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.