How to check if a file exists using templates?

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 only the name and version number. I tried test , but this did not work:

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

How to check if a file exists?

+4
source share
6 answers

Just check if the shell has expanded the template.
If the template can match only one file (for example, there is only one backup file for each revision), you can use:

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

If the template can match multiple files:

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

You can 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 .

+4
source

A slight variation on eugene y answers:

 test "$(echo name1.*.r9.bz2)" != "name1.*.r9.bz2" && echo exists 
+2
source

I would use:

 if ls name1.*.r9.bz2 &> /dev/null ; then echo exists fi 
+2
source

Related posts: Check if the template file exists in the shell script

You seem to have a good answer using the return value of ls.

+1
source

Try something like

 FILES=(`ls name1.*.r9.bz2`) if [ ${#FILES[@]} -gt 0 ]; then echo "Files!" else echo "No Files" fi 
0
source

Source: https://habr.com/ru/post/1306815/


All Articles