Команда GETOPTS не работает в моем сценарии оболочки - PullRequest
0 голосов
/ 12 сентября 2018

Кто-нибудь может мне помочь, пожалуйста?я написал скрипт и в моем скрипте я использовал GETOPTS для создания опций, но он не работает

он имел какую-то ошибку, и я проверял это в shellcheck.net и исправлял их, но он не работает

#!/bin/bash

while getopts 'n:c2rFt' option; do
case "$option" in
    n) export Field="$OPTARG"
       ;;
    c) #Question 1
       cat "$1" | awk '{print $1}' | sort | uniq -c | sort -nrk 1,1 > file1
       awk 'NR=="$Field" {print}' file1
       ;;
    2) #Question 2
       cat "$1" | awk '{ if($9 == 200) print $1,$9 }' | sort | uniq -c | sort -nrk 1,1 > file1
       awk 'NR=="$Field" {print}' file1
       ;;
    r)  #Question 3
        cat "$1" | awk '{print $1,$9}' | sort | uniq -c | sort -nrk 1,1 > file1
        awk 'NR=="$Field" {print}' file1
        ;;
    F)  #Question 4
        cat "$1" | awk '{if($9 >= 400 && $9 <= 451)} {print $1,$9}' | sort | uniq -c | sort -nrk 1,1 > file1
        awk 'NR=="$Field" {print}' file1
        ;;
    t)  #Question 5
        cat "$1" | awk '{print $1,$10}' | sort | uniq -c | sort -nrk 3,3 > file1
        awk 'NR=="$Field" {print}' file1
        ;;
    ?)
        echo "You used wrong option"    
        echo "USAGE: log_sum.sh [-n  N] (-c|-2|-r|-F|-t|-f) <filename>"
        echo " -n: Limit the number of results to N"
        echo " -c: shows th IP address makes the most number of connection attempts"
        echo " -2: shows th most number of seccessful attempts "
        echo " -r: shows th most common result codes and their IP addresses"
        echo " -F: shows the most common result codes that indicate failure"
        echo " -t: shows the IP addresses that get the most bytes sent to them"
        exit 1
        ;;
esac
done

1 Ответ

0 голосов
/ 12 сентября 2018

Ваша «бизнес-логика» не в том месте: ваш код предполагает, что пользователь сначала предоставит опцию -n. Это не требуется getopts. Вы должны написать программу такого типа в 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...