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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With