2

This works:

if [ /a/*/b/file.asd -nt /c/d/file.asd ]; then echo "found new file"; fi 

This doesn't work:

if [[ /a/*/b/file.asd -nt /c/d/file.asd ]]; then echo "found new file"; fi 

Can someone please explain why /*/ is not working with double brackets?

1

1 Answer 1

2

Shell globbing patterns potentially expand to more than one pathname. For example, if /a/*/b/file.asd expands to multiple pathnames, then the test that you are performing becomes nonsensical.

Also, shell globs are not expanded inside [[ ... ]]. From the bash manual:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]

If you know that you want to perform the test on a particular file, e.g. /a/x/b/file.asd, then use that pathname in the test. If you want to perform the test on all pathnames that matches that pattern, use a loop:

shopt -s nullglob dotglob for pathname in /a/*/b/file.asd; do if [[ $pathname -nt /c/d/file.asd ]]; then printf 'found new file: %s\n' "$pathname" fi done 

The nullglob and dotglob shell options are set so that the pattern is removed if it does not match anything and so that * catches any hidden directories.

Also, the test could be done with find, unless the pattern /a/*/b/file.asd expands to many thousands of pathnames:

find /a/*/b/file.asd -prune -type f -newer /c/d/file.asd 

This would expand the pattern /a/*/b/file.asd and use each of the pathnames that it expands to as a search path for find. The search paths are tested against /c/d/file.asd and the pathnames are printed if they are newer than that file. The -prune stops find from moving down into a search path, just in case any of them refers to a directory.

10
  • As i said in my post that the statement with single brackets WORKS, it actually checks all path names :) Commented Nov 6, 2019 at 14:18
  • 1
    @r.tihovs It can't, unless the pattern only ever expands to a single pathname. You'll get an error if it expands to multiple pathnames. Commented Nov 6, 2019 at 14:19
  • Yes indeed, the name is the same always, only the directory is changing Commented Nov 6, 2019 at 14:20
  • So in conclusion im interested why shell globs are not expanded inside [[ ... ]]. Can you please explain? Commented Nov 6, 2019 at 14:48
  • 1
    -name file.asd is redundant since it's going to be true for each of those files. Commented Nov 6, 2019 at 17:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.