-1

I have a simple if-statement that checks if a file exists in a directory. If it matches it returns OK, otherwise, it echos FAIL.

if [[  -f Foobarfile_"${TODAY}"*.txt ]]; then echo "OK"; else echo "Fail!"; fi

$TODAY is a date stamp having YYYY-MM-DD format.

If I have in the directory Foobarfile_2016-01-15_100.txt" as the only file, the if-statement will return true.

I am puzzled because if the directory has multiple files, the if-statement will return false. E.g. if it has another file called "Foobarfile_2016-01-15_101.txt"

It should basically check that as long as the directory has a filename that has today's date stamp, i.e.:

Foobarfile_2016-01-15_100.txt
Foobarfile_2016-01-15_101.txt
somethingelse_2016-01-15_102.txt
KrispyKreme_2016-01-14_98.txt
Foobarfile_2016-01-15_104.txt...

it should return true. Can anyone help with this problem?

codeforester
  • 39,467
  • 16
  • 112
  • 140
dat789
  • 1,923
  • 3
  • 20
  • 26

3 Answers3

2

If I understand you correctly, you want to test whether one or more files contain today's date. One way to do that would be to use an array:

shopt -s nullglob
files=( Foobarfile_"${TODAY}"*.txt )
if [[ ${#files} -ge 1 ]]; then
    echo "OK"
fi

shopt -s nullglob sets the nullglob shell option. With this option set, the array will be empty if no files match the pattern. Otherwise, a failed expansion would result in the array containing one element e.g. Foobarfile_2016-01-15*.txt.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • what does shopt - nullglob do? – dat789 Jan 15 '16 at 14:42
  • Tried your suggestion and seems to work. But, on another matter, shell seem to have lost autocomplete. e.g $ mv Foobarfile does not work anymore. I have to unset by executing shopt -u nullglob – dat789 Jan 15 '16 at 14:46
  • Hmm I can't see why this would affect it; is it broken if you try on a newly opened shell? – Tom Fenech Jan 15 '16 at 14:49
  • 1
    Older bash autocompletion support is known to have issues when options are set to non-default values. See my answer [here](http://stackoverflow.com/a/29909046/258523) for a bit about this and a link to a commit that fixes it. – Etan Reisner Jan 15 '16 at 16:13
0

if Statement is of type [[ expression ]]
no pathname expansion shall happen, see the Bash Manual.

In your case, expression [[ will search for file with name Foobarfile_2016-01-15*.txt which does not exist.

That's you are getting "Fail" print.

Varun
  • 447
  • 4
  • 9
0
[ -f Foobarfile_$(date --rfc-3339=date)*.txt ] && echo "OK" || echo "no joy"
Calvin Taylor
  • 664
  • 4
  • 15