0

この単純なスクリプトがあるとします

#! /bin/sh

if [ $# -ne 2 ]
then
        echo "Usage: $0 arg1 arg2"
        exit 1
fi

head $1 $2

## But this is supposed to be:
## if -f flag is set, 
##      call [tail $1 $2]
## else if the flag is not set
##      call [head $1 $2]

では、スクリプトに「フラグ」チェックを追加する最も簡単な方法は何ですか?

ありがとう

4

2 に答える 2

1
fflag=no
for arg in "$@"
do
    test "$arg" = -f && fflag=yes
done

if test "$fflag" = yes
then
    tail "$1" "$2"
else
    head "$1" "$2"
fi

この単純なアプローチも実行可能かもしれません:

prog=head
for i in "$@"
do
    test "$i" = -f && prog=tail
done

$prog "$1" "$2"
于 2012-07-11T22:31:14.123 に答える
1

オプションを解析するとき、私は通常「case」ステートメントを使用します。

case "$1" in
    -f) call=tail ; shift ;;
    *)  call=head ;;
esac

$call "$1" "$2"

位置パラメータを引用することを忘れないでください。スペースを含むファイル名またはディレクトリ名が含まれる場合があります。

Bourneシェルの代わりにbashなどを使用できる場合は、getopts組み込みコマンドなどを使用できます。詳細については、bashのmanページを参照してください。

于 2012-07-11T22:32:41.813 に答える