Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to check if a glob pattern matches any file [duplicate]

Tags:

bash

shell

glob

I wrote a shell script to check if a binary is present:

#!/usr/local/bin/bash

if [ -e "/path/to/a/binary/file/app.bin" ]; then 
     echo "INFO: application has been built successfully" 
else 
     echo "ERROR: application couldn't be built". 
fi

It works fine and gives expected results. However if there are many applications with similar name (say app1.bin, app2.bin etc) and I want to test for "app*.bin" the if condition fails:

#!/usr/local/bin/bash

    if [ -e "/path/to/a/binary/file/app*.bin" ]; then 
         echo "INFO: application has been built successfully" 
    else 
         echo "ERROR: application couldn't be built". 
    fi

How can i correct the if condition to search for existence of any binary with app as name i.e. app*.bin

like image 336
Yash Avatar asked Oct 18 '25 14:10

Yash


2 Answers

An alternative is to use compgen -G: it will generate a list of matching files or it will exit with an error status if nothing matches. With compgen you need quotes to prevent expansion.

if compgen -G "/path/to/a/binary/file/app*.bin" > /dev/null; then 
     echo "INFO: application has been built successfully" 
else 
     echo "ERROR: application couldn't be built". 
fi
like image 166
Andrea Corbellini Avatar answered Oct 21 '25 08:10

Andrea Corbellini


glob matching does not work inside quotes. Even if you did remove it, the condition will fail if multiple files are returned from the glob match, because the -e will work for single file only.

In bash you can do this,

# the nullglob will let the unmatched glob to handled properly
shopt -s nullglob
fileList=(/path/to/a/binary/file/app*.bin)

if [ "${#fileList[@]}" -ge 1 ]; then
     echo "INFO: application has been built successfully" 
else
     echo "ERROR: application couldn't be built". 
fi

# This line is optional. This is just to ensure the nullglob option is 
# reset after our computation
shopt -u nullglob
like image 21
Inian Avatar answered Oct 21 '25 07:10

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!