the problem is the line
if [ -f `sources/*.bak` ]
backticks `
have a special meaning in bash: they are used to evaluate a command and return its output.
E.g. If your username is frodl then
if [ -f `whoami` ]
will check if there is a file named frodl
.
So if you write sources/*.bak
, it will first try to glob the term sources/*.bak
, but since there are no files in the sources/
directory with a .bak
extension, the term will not be expanded. It will then try to run the literal term sources/*.bak
, which is no valid command (actually you can have a file called sources/*.bak
(a filename with an asterisk at the beginning; shudder!), but it seems that you don't. However, this file would have a .bak
extension, something we ruled out before.)
If you do have a file sources/deletemyharddisk.bak
, then the term sources/*.bak
will expand to that string, and then try to execute it (potentially deleting your harddisk).
So what you need to do is use ordinary quotes.
backupfiles=sources/*.bak
if [ "x${backupfiles}" = "xsources/*.bak" ]; then
echo "no .bak files" 1>&2
else
echo "there are .bak files"...
fi
This will first try to expand the sources/*.bak
term into the backupfiles
variable. If there are any bak-files, this will become a string of all filenames; if there are none, this will stay the unexpanded string.
If you then compare the result with the literal (unexpanded) sources/*.bak
you can tell, whether an expansion took place (because there are matching files) or not.
a better approach
however, there is little reason to first check if there are files and then delete them.
a simpler approach is to just remove all the files that match a given pattern.
find
can do that for you:
find sources/ -maxdepth 1 -type f -name "*.bak" -delete
(this will search the first level (-maxdepth 1
) of the sources/
directory for files (-type f
; rather than directories or symlinks or other things), which end in .bak
(-name "*.bak"
) and then remove them (-delete
)
Do not parse ls
Another issue with your code is
target_files=`echo -n $(ls sources/{*.c,*.h})`
for i in $target_files
...
You should never parse the output of ls
.
Instead use something like
for i in sources/*.c sources/*h
do
#...
done
elif ["" == "$1"]
, missing double quotes around variable expansions, andtarget_files
should be an array; use ofls
instead of directly using wildcards. – Gilles 'SO- stop being evil' Jan 12 '17 at 13:59