我經常使用這個 bash 命令
find ~ -type f -name \*.smt -exec grep something {} /dev/null \;
所以我試圖把它變成一個簡單的 bash 腳本,我會像這樣呼叫它
findgrep ~ something --mtime -12 --name \*.smt
感謝這個答案,我設法讓它像這樣作業:
if ! options=$(getopt -o abc: -l name:,blong,mtime: -- "$@")
then
exit 1
fi
eval "set -- $options"
while [ $# -gt 0 ]
do
case $1 in
-t|--mtime) mtime=${2} ; shift;;
-n|--name|--iname) name="$2" ; shift;;
(--) shift; break;;
(-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
(*) break;;
esac
shift
done
if [ $# -eq 2 ]
then
dir="$1"
str="$2"
elif [ $# -eq 1 ]
then
dir="."
str="$1"
else
echo "Need a search string"
exit
fi
echo "find $dir -type f -mtime $mtime -name $name -exec grep -iln \"$str\" {} /dev/null \;"
echo "find $dir -type f -mtime $mtime -name $name -exec grep -iln \"$str\" {} /dev/null \;" | bash
但是最后一行 - 將命令回顯到 bash 中 - 似乎完全野蠻,但它有效。
有沒有更好的方法來做到這一點?以某種方式嘗試直接執行 find 命令沒有輸出,而在 bash 中運行 echo'ed 則可以。
uj5u.com熱心網友回復:
ame $name -e
它仍然沒有被參考。用 shellcheck 檢查你的腳本。
find "$dir" -type f -mtype "$mtime" -name "$name" -exec grep -iln "$str" {} ';'
您可能想退后一步,做一些關于 sh 中的參考和擴展的研究,find以及glob. find程式需要文字 glob 模式,并且不帶引號的變數擴展經歷檔案名擴展,*.smt變為表示檔案名的單詞串列,而find希望模式不是擴展的結果。
我可以拋出:man find, man 7 glob, https://www.gnu.org/software/bash/manual/html_node/Quoting.html https://mywiki.wooledge.org/BashFAQ/050
https://mywiki.wooledge.org/ BashGuide/Parameters#Parameter_Expansion
在您開始決定如何將可變數量的引數傳遞給 之前find,我鼓勵您研究 Bash 陣列。我會做:
#!/bin/bash
fatal() {
echo "$0: ERROR: $*" >&2
exit 1
}
args=$(getopt -o abc: -l name:,iname:,mtime: -- "$@") || exit 1
eval "set -- $args"
findargs=() # bash array
while (($#)); do
case $1 in
-t|--mtime) findargs =(-mtime "$2"); shift; ;;
-n|--name) findargs =(-name "$2"); shift; ;;
--iname) findargs =(-iname "$2"); shift; ;;
--) shift; break; ;;
-*) fatal "unrecognized option $1"; ;;
*) break; ;;
esac
shift
done
if (($# == 2)); then
dir="$1"
str="$2"
elif (($# == 1)); then
dir="."
str="$1"
else
fatal "Need a search string"
fi
set -x
find "$dir" -type f "${findargs[@]}" -exec grep -iln "$str" /dev/null {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450365.html
標籤:重击
下一篇:如何為目錄中的每個檔案添加后綴
