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
  • 81,915
  • 7
  • 76
  • 137
Yash
  • 2,654
  • 7
  • 23
  • 38
  • 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
  • 16,400
  • 3
  • 50
  • 66
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
  • 71,145
  • 9
  • 121
  • 139
  • @F.Hauri: I do have the `nullgob` option set right(`shopt -s nullglob `)? – Inian Jun 13 '17 at 06:54
  • 1
    Oh yes, sorry: I was too quick... (I don't use `nullglob`). Testing with `-e` seem clean and efficient. Generally I try to not use `shopt` to prevent strong debugging operations. – F. Hauri Jun 13 '17 at 06:59