
-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 -
結果
haetex "TODO"
期待される出力は出力と同じです。合格!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 -