I have a bash script that I want to take some optional input arguments, followed by either a filename or a file specification containing wildcards.
If I run
getopts_problem.sh -td *.txt
the script happily outputs a list of .txt files in the current directory:
file is readme.txt letter_to_editor.txt someotherfile.txt
If I run getopts_problem.sh -td *.ABC
the script outputs
file is *.ABC
There are no files in the current directory with the extension ".ABC". For some reason, then, the script interprets "*.ABC" as a filename. How can I get the script to recognise "*.ABC" as a filename expression to be expanded, rather than an actual filename? The code is as follows:
# !/bin/sh
doDry=0
doTimestamp=0
while getopts ":dt" OPT;
do
case $OPT in
d ) doDry=1 ;;
t ) doTimestamp=1 ;;
? ) echo 'Bad options used. '
exit 1 ;;
esac
done
shift $(($OPTIND - 1))
fileList=$@
for file in "$fileList"
do
echo file is $file
done
exit 0
The wildcard patterns are expanded by
bash
before executing your script. Not the shell that interprets the script, but the one you run it from. And whether it keeps pattern, passes nothing or fails depends onnullglob
,failglob
and some such options (seeman bash
).Also, in
for file in "$fileList"
quotes explicitly tell shell not to expand the variable.