為什麼此選項在此 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只設定一個變量,例如

-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 -

相關內容