shell - BASH script : usage displays even if you provide a switch without argument -
i've tried many ways , i'm stumped. when try sudo admpanel -a
without argument script displays message usage() method instead of error msg i've built it. on other hand if sudo admpanel -a firstname
displays me error msg portion. if enter sudo admpanel -a firstname lastname
functions way supposed to. below script :
#!/bin/bash # program name : admpanel.sh progname=${0##*/} version="1.0" script_shell=${shell} usage() { echo "usage: ${progname} [-h|--help ] [-a|--add] [-r|--remove] [-d|--display] [-c|--check] [argument_1] [argument_2]" } help_message() { cat <<- _eof_ ${progname} ${version} add/remove/display user(s) on admin panel. please note password hardcoded. please consult system administrator if don't know it. $(usage) options: -h, --help displays help. -a, --add add user -r, --remove remove user -d, --display display users -c, --check check specific user example: ${progname} -a firstname lastname ${progname} --add firstname lastname ${progname} -r firstname lastname ${progname} --remove firstname lastname ${progname} -d ${progname} -display ${progname} -c firstname lastname ${progname} --check firstname lastname _eof_ } verify() { echo "are sure want this?" read answer } add_employee() { echo adding user } remove_employee() { echo removing user } display_users() { echo displaying users } check_user() { echo checking users } if [ "$#" -le 1 ]; usage exit 1 elif [[ $user != "root" ]]; echo "this script must run root!" exit 1 elif [[ ($1 == "-h" ) || ($1 == "-help") || ($1 == "--help") ]]; help_message exit 0 elif [[ ($1 == "-a") || ($1 == "-add") || ($1 == "--add") ]]; if [[ -z "$3" ]]; echo "error: first name , last name wasn't provided" echo "usage: ${progname} -a firstname lastname" exit 1 elif [[ (-z "$2") || (-z "$3") ]]; echo "error: either first name or last name wasn't provided or both" echo "usage: ${progname} -a firstname lastname" exit 1 else read -p "are sure want continue? <y/n> " prompt if [[ $prompt == "y" || $prompt == "y" || $prompt == "yes" || $prompt == "yes" ]]; add_employee exit 0 else exit 0 fi fi elif [[ ($1 == "-r") || ($1 == "-remove") || ($1 == "--remove") ]]; remove_employee exit 0 elif [[ ($1 == "-d") || ($1 == "-display") || ($1 == "--display") ]]; display_users exit 0 elif [[ ($1 == "-c") || ($1 == "-check") || ($1 == "--check") ]]; check_user exit 0 else echo went wrong try again... exit 1 fi
please advise. -thanks in advance.
it's because of line:
if [ "$#" -le 1 ];
it says "less or equal to 1". therefore, message triggers when give 1 argument, namely -a
.
you should instead change "strictly less than":
if [ "$#" -lt 1 ];
Comments
Post a Comment