I use this bash command often
find ~ -type f -name \*.smt -exec grep something {} /dev/null \;
so I am trying to turn it into a simple bash script that I would invoke like this
findgrep ~ something --mtime -12 --name \*.smt
However I get stuck with processing the command line options with GNU getopt like this:
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
which does not seem to work - I suspect because the $name
variable gets passed in quotes to find
.
How do I fix that?
CodePudding user response:
set -- $options
Is invalid (and it's not quoted). It's eval "set -- $options"
. Linux getopt
outputs properly quoted string to be eval-ed.
mtime="${mtime%\'}" mtime="${mtime#\'}" dir="${dir%\'}" dir="${dir#\'}"
Remove it. That's not how expansions work.
-name $name
It's not quoted. You have to quote it upon use.
-name "$name"
Check your scripts with shellcheck.