Got a bit of a peculiar issue in bash. I want to author a script that takes a prefix of a file name and deletes all files that begin with that prefix and end in some given suffixes. To do this, I have the following line of code:
#!/bin/bash
if [ $# -lt 1 ]; then
echo "Please provide an argument";
exit 1
fi
# Ending dot already included in $1
rm -f $1"aux" $1"bbl" $1"blg" $1"synctex.gz" $1"log"
# But even if you call it wrong...
rm -f $1".aux" $1".bbl" $1".blg" $1".synctex.gz" $1 ".log"
exit 0
Unfortunately, when I call my script (which is called cleanlatex
), as intended:
cmd$ cleanlatex lpa_aaai.
only the .aux file is deleted. Clearly rm -f
doesn't expand its application to all arguments, which is what would've been done if I explicitly ran rm -f lpa_aaai.aux lpa_aaai.bbl ...
. What am I doing wrong here?
Edit: To answer @Etan's question, this is what I see when I add those commands:
+ '[' 1 -lt 1 ']'
+ rm -v lpa_aaai.aux lpa_aaai.bbl lpa_aaai.blg lpa_aaai.synctex.gz lpa_aaai.log
removed ‘lpa_aaai.aux’
removed ‘lpa_aaai.bbl’
removed ‘lpa_aaai.blg’
removed ‘lpa_aaai.synctex.gz’
removed ‘lpa_aaai.log’
+ rm -v lpa_aaai..aux lpa_aaai..bbl lpa_aaai..blg lpa_aaai..synctex.gz lpa_aaai. .log
rm: cannot remove ‘lpa_aaai..aux’: No such file or directory
rm: cannot remove ‘lpa_aaai..bbl’: No such file or directory
rm: cannot remove ‘lpa_aaai..blg’: No such file or directory
rm: cannot remove ‘lpa_aaai..synctex.gz’: No such file or directory
rm: cannot remove ‘lpa_aaai.’: No such file or directory
rm: cannot remove ‘.log’: No such file or directory
The second set, consisting of the cannot remove
messages, does not concern me: I only have those removals as a fail-safe anyway. This did exactly what I needed. Thank you.
It's not clear what your problem actually is; however, you can reduce your script to two lines of bash
:
: ${1?Please provide an argument}
rm -f "$1".{aux,bbl,log,synctex.gz,log}
The first line has the same effect as your if
statement, using standard POSIX parameter expansion.
The second line properly quotes $1
and uses brace expansion to produce the sequence of file names with the desired list of suffixes. It makes the simplifying assumption that the user typed the basename of the files without the trailing period: who would type foo.
when foo
would suffice? You're already making the assumption that there are not files named (for instance) foo.aux
and foo..aux
, so you might as well make an assumption that makes for less work.
I removed exit 0
because either rm
succeeds and your script will exit with status 0 anyway, or rm
fails, in which case you shouldn't be exiting with 0 status, but whatever status rm
exits with.