在 getopt 中处理 glob
Processing globs in getopt
我经常使用这个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 in
-t|--mtime) mtime= ; shift;;
-n|--name|--iname) name="" ; shift;;
(--) shift; break;;
(-*) echo "[=12=]: error - unrecognized option " 1>&2; exit 1;;
(*) break;;
esac
shift
done
echo "done"
echo $@
if [ $# -eq 2 ]
then
echo "2 args"
dir=""
str=""
elif [ $# -eq 1 ]
then
dir="."
str=""
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"
。 Linux getopt
输出正确引用的字符串为 eval-ed.
mtime="${mtime%\'}"
mtime="${mtime#\'}"
dir="${dir%\'}"
dir="${dir#\'}"
删除它。这不是扩展的工作方式。
-name $name
没有引用。使用时必须引用.
-name "$name"
用 shellcheck 检查你的脚本。
我经常使用这个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 in
-t|--mtime) mtime= ; shift;;
-n|--name|--iname) name="" ; shift;;
(--) shift; break;;
(-*) echo "[=12=]: error - unrecognized option " 1>&2; exit 1;;
(*) break;;
esac
shift
done
echo "done"
echo $@
if [ $# -eq 2 ]
then
echo "2 args"
dir=""
str=""
elif [ $# -eq 1 ]
then
dir="."
str=""
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"
。 Linux getopt
输出正确引用的字符串为 eval-ed.
mtime="${mtime%\'}" mtime="${mtime#\'}" dir="${dir%\'}" dir="${dir#\'}"
删除它。这不是扩展的工作方式。
-name $name
没有引用。使用时必须引用.
-name "$name"
用 shellcheck 检查你的脚本。