bash 脚本中的参数数量灵活

Flexible number of parameters in a bash script

我正在使用以下类型的 bash 代码。我将一些信息存储在日志文件中,该文件的名称在 bash 脚本中定义。

LOGNAME="/tmp/ETH"
LOG_FILE="${LOGNAME}.log"    

function exit_error()
{
    case "" in
        100 )
            echo "Bad arguments supplied - Enter help"
            echo "Bad arguments supplied - Enter help" >> "${LOG_FILE}"
            ;;      
        101 )
            echo "Illegal number of parameters"
            echo "Illegal number of parameters" >> "${LOG_FILE}"
            ;;       
        * )
            ;;
    esac    
    exit 1;
}

function current_status()
{
    INT_STATUS=$(cat /sys/class/net/eth1/operstate)
    echo "status : $INT_STATUS"
    echo "status : $INT_STATUS" >> "${LOG_FILE}"
}

function connect_eth()
{
    ...
}

...

case "" in
    current_status )
        if [ "$#" -ne 1 ]
        then
            exit_error 101
        else
            current_status
        fi
        ;;  
    connect_eth )
        if [ "$#" -ne 1 ]
        then
            exit_error 101
        else
            connect_eth
        fi
        ;;
    read_MAC_addr )
        if [ "$#" -ne 1 ]
        then
            exit_error 101
        else
            read_MAC_addr 
        fi      
        ;;  
    read_IP_addr )
        if [ "$#" -ne 1 ]
        then
            exit_error 101
        else
            read_IP_addr
        fi
        ;;
    * )
        exit_error 100
        ;;
esac
exit 0; 

如果最后一个参数没有指定其他日志名称,我想修改脚本以使用指定的日志名称。但是,我想将我的 "exit_error 101" 保留在基于传递给脚本的参数数量的 switch case 中。有没有办法做到这一点 ?因为我不能修改 $# 变量。

应该是可以的。做这样的事情:

CMD=""
shift
# use provided logname or set to default if not found
LOGNAME="${1:-/tmp/ETH}
shift
LOGFILE="${LOGNAME}.log"
# now, since we shifted, you just have to check for $# -eq 0 to
# be sure there are no params left.

... your function definitions here ...

# exit 101 if there are some parameters left
if [ $# -ne 0 ]; then
  exit_error 101
fi

case "$CMD" in
  current_status)
    current_status
    ;;
  ...
  *)
    exit_error 100
    ;;
esac

如果您想要更大的灵活性,您始终可以使用 getopts 和命名参数。通常更容易维护。

而且,如果我是你,我也会在 case 语句之前集中处理错误,以避免在所有地方重复相同的检查。