4

I have a directory with full svn backups named like this:

name1.20100412.r9.bz2
name1.20100413.r10.bz2
name2.20100411.r101.bz2
name3.20100412.r102.bz2
...

I need to check if a backup file exists using name and revision number only. I tried test but it didn't work:

if [ -e name1.*.r9.bz2 ]; then echo exists; fi
[: too many arguments

How can I test if file exists?

planetp
  • 14,248
  • 20
  • 86
  • 160
  • What does `echo name1.*.r9.bz2` say? It looks like you have more than one revision 9 backup there! – Jens May 16 '12 at 12:45
  • Good answers there: http://stackoverflow.com/questions/6363441/check-if-a-file-exists-with-wildcard-in-shell-script . Simplest way: use `ls`. Best way: use `find`. – jrouquie Nov 02 '14 at 10:28

6 Answers6

3

You could do:

shopt -s nullglob
set -- name1.*.r9.bz2
if [ -n "$1" ]; then echo exists; fi

or

pattern="name1.*.r9.bz2"
if [ "$(echo $pattern)" != "$pattern" ]; then echo exists; fi

Edit: Added shopt -s nullglob.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
2

A slight variation on eugene y's answer:

test "$(echo name1.*.r9.bz2)" != "name1.*.r9.bz2" && echo exists
michaeljt
  • 1,106
  • 8
  • 17
2

Just check if the shell has expanded the pattern. This works in sh and bash:

pattern="name1.*.r9.bz2"

if [ "$(echo $pattern)" != "$pattern" ]; then
    echo exists
fi

P.S. If the pattern itself can be a valid filename, you can add a -e check:

if [ -e "$pattern" -o "$(echo $pattern)" != "$pattern" ]; then
    echo exists
fi
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

I would use:

if ls name1.*.r9.bz2 &> /dev/null ; then
  echo exists
fi
Marco Leogrande
  • 8,050
  • 4
  • 30
  • 48
-1

Related post: Check if a file exists with wildcard in shell script

It seems to have a good answer, using the return value of ls.

Community
  • 1
  • 1
adam.r
  • 247
  • 2
  • 12
-1

Try something like

FILES=(`ls name1.*.r9.bz2`)
if [ ${#FILES[@]} -gt 0 ]; then
  echo "Files!"
else
  echo "No Files"
fi
Josh Knauer
  • 1,744
  • 2
  • 17
  • 29