问题
I am trying to write a script that will operate on selected files.
#!/bin/bash
#ytest
lastArgNo=$#
sPattern=${!lastArgNo}
echo "operating on $sPattern"
#do operation on $sPattern
for sFile in $sPattern do
#do something with each file
done
If I start this script with Parameters *.JPG I get
operating on IMG_1282.JPG
which is the last file found for pattern *.JPG and only this file is being processed. I need the actual file pattern that is given on the commandline. Thanks in advance.
回答1:
You cannot get the actual pattern: the shell has already expanded it before launching your script. You do get the actual files as arguments, so what you should be doing is iterating over all the arguments:
#!/bin/bash
echo "operating on $# files"
for file; do
# do something with each "$file"
done
What you are doing is setting lastArgNo to the number of args, the using indirect variable expansion to set sPattern to the value of the last argument. If you did arg=1; sPattern=${!arg}
you would set sPattern to the first argument.
来源:https://stackoverflow.com/questions/28833856/prevent-globbing-in-a-bash-script