我經常使用這個 bash 命令
find ~ -type f -name \*.smt -exec grep something {} /dev/null \;
所以我試圖把它變成一個簡單的 bash 腳本,我會像這樣呼叫它
findgrep ~ something --mtime -12 --name \*.smt
但是,我無法像這樣使用 GNU getopt 處理命令列選項:
if ! options=$(getopt -o abc: -l name:,blong,mtime: -- "$@")
then
# something went wrong, getopt will put out an error message for us
exit 1
fi
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
echo "done"
echo $@
if [ $# -eq 2 ]
then
echo "2 args"
dir="$1"
str="$1"
elif [ $# -eq 1 ]
then
dir="."
str="$1"
echo "1 arg"
else
echo "need a search string"
fi
echo $dir
echo $str
echo $mtime
echo "${mtime%\'}"
echo "${mtime%\'}"
echo '--------------------'
mtime="${mtime%\'}"
mtime="${mtime#\'}"
dir="${dir%\'}"
dir="${dir#\'}"
echo $dir $mtime $name
# grep part not in yet
find $dir -type f -mtime $mtime -name $name
這似乎不起作用 - 我懷疑是因為$name變數以引號傳遞給find.
我該如何解決?
uj5u.com熱心網友回復:
set -- $options
無效(并且未參考)。是eval "set -- $options"。Linuxgetopt輸出正確參考的字串以進行評估。
mtime="${mtime%\'}" mtime="${mtime#\'}" dir="${dir%\'}" dir="${dir#\'}"
去掉它。這不是擴展的作業方式。
-name $name
它沒有被參考。您必須在使用時參考它。
-name "$name"
用 shellcheck 檢查你的腳本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451494.html
下一篇:用戶輸入變數并grep模式檔案
