簡體   English   中英

Bash腳本用作wc命令

[英]Bash Script to function as wc command

我正在嘗試使用getopts創建一個腳本,該腳本可以像wc工作。 問題是當我同時使用兩個開關時會卡住。 劇本:

while getopts l:w:c: choice
do
         case $choice in
               l) wc -l $OPTARG;;
               w) wc -w $OPTARG;;
               c) wc -c $OPTARG;;
               ?) echo wrong option.
         esac
done

當我使用./script.sh -l file運行此腳本時,它可以工作,但是當我使用./script -wl file它將進入無限循環。 誰能解釋發生了什么事以及如何解決?

您使用不正確。 根據getopts手冊

如果一個字母后跟一個冒號 ,則該選項應帶有一個參數。

在您的示例中,您沒有傳遞-w-l選項的參數;

正確用法是:

./script -w file1 -l file2

這將正確處理兩個選項。

否則,要支持不帶參數的選項,就可以像這樣使用不帶冒號的選項:

while getopts "hl:w:c:" choice

在這里,選項h不需要參數,但是l,w,c支持一個。

您需要在case語句中構建選項,然后執行wc

# Set WC_OPTS to empty string
WC_OPTS=();
while getopts lwc choice
do
     case $choice in
            l) WC_OPTS+='-l';;
            w) WC_OPTS+='-w';;
            c) WC_OPTS+='-c';;
            ?) echo wrong option.
     esac
done
# Call wc with the options
shift $((OPTIND-1))
wc "${WC_OPTS[@]}" "$@"

要添加其他注釋。 我方便使用的wc版本似乎可以處理以下選項:

#!/bin/bash

options=()
files=()

while (( $# > 0 )) ; do
    if [[ "$1" = --help || "$1" = --version ]] ; then
        wc "$1"   # print help-message or version-message
        exit
    elif [[ "${1:0:1}" = - ]] ; then
        while getopts cmlLw opt ; do
            if [[ "$opt" = '?' ]] ; then
                wc "$1"   # print error-message
                exit
            fi
            options+="$opt"
        done
        shift $((OPTIND-1))
        OPTIND=1
    else
        files+="$1"
        shift
    fi
done

wc "${options[@]}" "${files[@]}"

(可以通過對五個可能選項中的每個選項使用單獨的變量來進一步完善上述內容,以突出顯示以下事實: wc不在乎其選項出現的順序,也不在乎給定選項是否出現多個次)。

Got a workaround.

#!/bin/bash

if [ $# -lt 2 ]
then

    echo not a proper usage
    exit

fi

file=$2

while getopts wlc choice

do

    case $choice in 

        l) wc -l $file
            ;;
        w) wc -w $file
            ;;
        c) wc -c $file
            ;;
        ?) echo thats not a correct choice

    esac
done

I think I got obsessed with OPTARG, thanks everyone for your kind help 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM