GETOPTS命令在我的Shell脚本中不起作用

时间:2018-09-12 17:39:34

标签: shell unix

有人可以帮我吗? 我写了一个脚本,在脚本中我使用GETOPTS进行选择,但是它不起作用

它有一些错误,我在shellcheck.net中对其进行了检查并修复了它们,但是它不起作用

WebBrowser

1 个答案:

答案 0 :(得分:0)

您的“业务逻辑”放置在错误的位置:您的代码假定用户将首先提供-n选项。 getopts并不是 required 。您必须通过3个阶段来编写此类程序:选项解析,验证和操作:

#!/bin/bash
usage() {
    local program=$(basename "$0")
    cat <<END_USAGE >&2
USAGE: $program -n N (-c|-2|-r|-F|-t|-f) <filename>
 -n: Limit the number of results to N
 -c: shows th IP address makes the most number of connection attempts
 -2: shows th most number of seccessful attempts 
 -r: shows th most common result codes and their IP addresses
 -F: shows the most common result codes that indicate failure
 -t: shows the IP addresses that get the most bytes sent to them
END_USAGE
}

# Option parsing
while getopts ':n:c2rFt' option; do
    case "$option" in
        n) num_results=$OPTARG ;;
        c) show_connections=yes ;;
        2) show_successful=yes ;;
        r) show_common_results=yes ;;
        F) show_common_failures=yes ;;
        t) show_most_bytes=yes ;;
        ?) echo "Error: unknown option $OPTARG"; usage; exit 1 ;;
    esac
done
shift $((OPTIND - 1))
filename=$1

# Validation
if [[ -z $num_results ]]; then
    echo "Error: you must provide the -n option" >&2
    usage >&2
    exit 1
fi
if [[ -z $filename ]]; then
    echo "Error: you must provide a filename" >&2
    usage >&2
    exit 1
fi

# Actions

# helper function to encapsulate repeated code
top_results() { sort | uniq -c | sort -nrk 1,1 | sed "${num_results}q"; }

if [[ $show_connections == yes ]]; then
    awk '{print $1}' "$filename" | top_results
fi
if [[ $show_successful == yes ]]; then
    awk '$9 == 200 {print $1,$9}' "$filename" | top_results
fi
if [[ $show_common_results == yes ]]; then
    awk '{print $1,$9}' "$filename" | top_results
fi
if [[ $show_common_failures == yes ]]; then
    awk '$9 >= 400 && $9 <= 451 {print $1,$9}' "$filename" | top_results
fi
if [[ $show_most_bytes == yes ]]; then
    awk '{print $1,$10}' "$filename" | top_results
fi