默认标志选项获取操作

时间:2019-02-25 16:58:15

标签: bash getopts

如果某人运行-9并且在该标志后没有为OPTARG放置任何东西,我希望将ops默认设置为-8标志,或者我可以检查OPTARG是否为空并将空值替换为一个基数值。

ft1和ftx只是格式函数。

当我运行goat -8时,它会打印出该文件

当我运行goat -9 SEARCH STRING时,它仅显示该搜索字符串的结果文件。

如果我运行goat -9且未放置搜索字符串,则它不会执行任何操作,因为OPTARG为空,因此grep没有要搜索的内容。

如果用户未在-9之后输入字符串,我希望能够将-8更改为goat -9

    function goat() {
        local OPTIND
        local OPTARG
            if [ "$1" = "" ] ;
            then ft1 ;
            printf "

        This command requires an OPTION. Refer to the help menu (-h) for assistance.

    " | layoutcc
    ft1 ;
    fi

    while getopts ":h89:" opt;
    do case $opt in 

     8) for file in analysis/connection_history.txt ; do ftx $file | layoutcc ; 
                printf "%s" "$(<$file)"                                                    
                echo ;
                ft1 ;
                done 
    ;;

    9) grep_expr=$OPTARG

       for file in analysis/connection_history.txt ; do
            ftx "$file" | layoutcc
            grep "$grep_expr" $file | perl -ne 'print if /-201[8-9]/' | 
            perl -pe 's/......-2019/\e[1;32m$&\e[0m/g' 
                echo
                ft1
                done 
                ;;

function ft1
{
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' = 
}   

function ft2
{
ft1 ;
ft1
}

function ftx
{ 
ft1 ;
echo "                         File Name: $1    $(grep -h "Created on" *-Report.txt | head -n1)" 
ft1
}       

function fsx
{
ft1 ;
echo "                         File Name: $1"
ft1
}

1 个答案:

答案 0 :(得分:0)

我将从选项解析代码中删除业务逻辑:

grep_expr=""
has_8=false
has_9=false

while getopts ":h89:" opt; do
    case $opt in 
        h) do_some_h_thing ;;
        8) has_8=true ;;
        9) has_9=true; grep_expr=$OPTARG ;;
        :) echo "Error: missing argument for option -$OPTARG" >&2; exit 1 ;;
        *) echo "Error: unknown option -$OPTARG" >&2; exit 1 ;;
     esac
done
shift $((OPTIND - 1))

if $has_8 || ($has_9 && [[ -z $grep_expr ]]); then
    for file in analysis/connection_history.txt ; do
        ftx $file | layoutcc
        printf "%s" "$(<$file)"   # why not `cat "$file"` ?                                                    
        echo ;                    #
        ft1 ;
    done 
elif $has_9; then
   for file in analysis/connection_history.txt ; do
        ftx "$file" | layoutcc
        # following pipeline can be greatly simplified
        grep "$grep_expr" $file |
          perl -ne 'print if /-201[8-9]/' | 
          perl -pe 's/......-2019/\e[1;32m$&\e[0m/g' 
        echo
        ft1
    done 
 else
    echo "Error: you must use one of '-8' or '-9 basic_regex'" >&2
    exit 1
fi
相关问题