このBashスクリプトでこのオプションが機能しないのはなぜですか?

このBashスクリプトでこのオプションが機能しないのはなぜですか?

-i | --ignore-caseエラー処理オプションを含めるために、次の機能を拡張しています。

#!/bin/sh
[ $# -ne 1 ] && echo "1 argument is needed" && exit 1
find $HOME -type f -name "*.tex" -exec grep -il "$1" {} + | vim -

拡張コード

#!/bin/sh
################################
# Check if parameters options  #
# are given on the commandline #
################################
while (( "$#" )); do
   case "$1" in
    -h | --help)
        echo "help menu"
        exit 0
        ;;
    -i | --ignore-case)
        [ $# -ne 2 ] && echo "1 argumenst i needed" && exit 1
        find $HOME -type f -name "*.tex" -exec grep -il "$1" {} + | vim -
        exit 0
        ;;
     -*)
        echo "Error: Unknown option: $1" >&2
        exit 1
        ;;
      *) # No more options
        break
        ;;
   esac

   shift # not sure if needed
done

# Do this if no cases chosen
[ $# -ne 1 ] && echo "1 argument is needed" && exit 1
find $HOME -type f -name "*.tex" -exec grep -l "$1" {} + | vim -

結果

  1. haetex "TODO"。期待される出力は出力と同じです。合格!
  2. haetex -i "TODO"。期待される結果:大文字と小文字を無視して検索します。結果:空のファイル。

このオプションが-iここで機能しないのはなぜですか?

ベストアンサー1

grep検索文字列の代わりにテストしたばかりのオプションが含まれているので、大文字と小文字を検索-iに変更してください。$2$1

find $HOME -type f -name "*.tex" -exec grep -il "$2" {} + | vim -

case複数のオプションを処理するには、ステートメントで1つの変数のみを設定することをお勧めします。

-i | --ignore-case)
    [ $# -ne 2 ] && echo "1 argumenst i needed" && exit 1
    case_option=-i
    ;;

その後、findループの後のコマンドは次のようになります。

find $HOME -type f -name "*.tex" -exec grep -l $case_option "$1" {} + | vim -

これは、検索文字列がパラメータの先頭に移動されたため$1に機能します。shift

したがって、スクリプト全体は次のようになります。

while (( "$#" )); do
   case "$1" in
    -h | --help)
        echo "help menu"
        exit 0
        ;;
    -i | --ignore-case)
        [ $# -ne 2 ] && echo "1 argumenst i needed" && exit 1
        case_option=-i
        ;;
     -*)
        echo "Error: Unknown option: $1" >&2
        exit 1
        ;;
      *) # No more options
        break
        ;;
   esac

   shift # not sure if needed
done

find $HOME -type f -name "*.tex" -exec grep -l $case_option "$1" {} + | vim -

おすすめ記事