3

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

melpomene
  • 84,125
  • 8
  • 85
  • 148
Yash
  • 2,944
  • 7
  • 25
  • 43
  • glob does not work inside quotes. Even if you did remove it, the condition will fail if multiple files are returned from the glob match – Inian Jun 13 '17 at 06:23
  • Hi @Inian, so what do you suggest. How should i change the code such that it solves my purpose. – Yash Jun 13 '17 at 06:25

2 Answers2

2

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
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
1

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
Inian
  • 80,270
  • 14
  • 142
  • 161