2

I ran the following in a directory with no files:

for file in *.20191017.*;do echo ${file}; done

what it returned was this:

*.20191017.*

which is little awkward since this was just a pattern and not the filename itself.

Can anyone please help on this?

francesco
  • 7,189
  • 7
  • 22
  • 49

2 Answers2

4

Found the reason for this anomaly (source: https://www.cyberciti.biz/faq/bash-loop-over-file/)

You can do filename expansion in loop such as work on all pdf files in current directory:

for f in *.pdf; do
    echo "Removing password for pdf file - $f"
done

However, there is one problem with the above syntax. If there are no pdf files in current directory it will expand to *.pdf (i.e. f will be set to *.pdf”). To avoid this problem add the following statement before the for loop:

#!/bin/bash
# Usage: remove all utility bills pdf file password 
shopt -s nullglob # expands the glob to empty string when there are no matching files in the directory.
for f in *.pdf; do
    echo "Removing password for pdf file - $f"
    pdftk "$f" output "output.$f" user_pw "YOURPASSWORD-HERE"
done
anishsane
  • 20,270
  • 5
  • 40
  • 73
3

The for loop simply iterates over the words between in and ; (possibly expanded by bash). Here, file is just the variable name. If you want to iterate between all files that are actually present, you can, for example, add a if to check if the ${file} really exists:

for file in *.20191017.*
do
   if [ -e "${file}" ]
   then
      echo ${file}
   fi
done

Or you can use, e.g., find

find . -name '*.20191017.*' -maxdepth 1

-maxdepth 1 is to avoid recursion.

francesco
  • 7,189
  • 7
  • 22
  • 49