在getopt中处理globs



我经常使用这个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

我该怎么解决?

set -- $options

无效(并且未引用(。它是eval "set -- $options"。Linuxgetopt输出正确引用的字符串以进行评估。

mtime="${mtime%'}"
mtime="${mtime#'}"
dir="${dir%'}"
dir="${dir#'}"

删除它。扩展不是这样工作的。

-name $name

它没有被引用。您必须在使用时引用它。

-name "$name"

使用shellcheck检查您的脚本。

最新更新