BASH脚本:即使您提供没有参数

时间:2015-05-29 18:28:14

标签: bash shell

我已经尝试了很多方法来做到这一点,我很难过。当我在没有参数的情况下尝试sudo admpanel -a时,脚本会显示来自usage()方法的消息,而不是我内置的错误信息。但另一方面,如果我sudo admpanel -a FirstName它显示错误消息部分。如果我输入sudo admpanel -a FirstName LastName,它的功能就像它应该的那样。以下是剧本:

#!/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 that the password is hardcoded.
    Please consult with the system administrator if you already don't know it.

    $(usage)

    Options:

    -h, --help      Displays help.
    -a, --add       Add user
    -r, --remove    Remove user
    -d, --display   Display all 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 you sure you want to do 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 ]; then
    usage
    exit 1
elif [[ $USER != "root" ]]; then
    echo "This script must be run as root!"
    exit 1
elif [[ ($1 == "-h" ) || ($1 == "-help") || ($1 == "--help") ]]; then
    help_message
    exit 0
elif [[ ($1 == "-a") || ($1 == "-add") || ($1 == "--add") ]]; then
    if [[ -z "$3" ]]; then
        echo "ERROR: First name and last name wasn't provided"
        echo "usage: ${PROGNAME} -a FirstName LastName" 
        exit 1  
    elif [[ (-z "$2") || (-z "$3") ]]; then
        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 you sure you want to continue? <y/N> " prompt
        if [[ $prompt == "y" || $prompt == "Y" || $prompt == "yes" || $prompt == "Yes" ]]; then
            add_employee
            exit 0
        else
            exit 0
        fi
    fi
elif [[ ($1 == "-r") || ($1 == "-remove") || ($1 == "--remove") ]]; then
    remove_employee
    exit 0
elif [[ ($1 == "-d") || ($1 == "-display") || ($1 == "--display") ]]; then
    display_users
    exit 0
elif [[ ($1 == "-c") || ($1 == "-check") || ($1 == "--check") ]]; then
    check_user
    exit 0
else
    echo something went wrong try again...
    exit 1
fi

请指教。 - 提前谢谢。

1 个答案:

答案 0 :(得分:1)

这是因为这一行:

if [ "$#" -le 1 ]; then

它表示“小于或等于 1”。因此,当您为其提供1个参数(即-a)时,将触发该消息。

您应该将其更改为“严格小于”:

if [ "$#" -lt 1 ]; then