I am wondering what’s the easiest way to check if a program is executable with bash, without executing it ? It should at least check whether the file has execute rights, and is of the same architecture (for example, not a windows executable or another unsupported architecture, not 64 bits if the system is 32 bits, …) as the current system.
Share
Take a look at the various test operators (this is for the test command itself, but the built-in BASH and TCSH tests are more or less the same).
You’ll notice that
-x FILEsays FILE exists and execute (or search) permission is granted.BASH, Bourne, Ksh, Zsh Script
TCSH or CSH Script:
To determine the type of file it is, try the file command. You can parse the output to see exactly what type of file it is. Word ‘o Warning: Sometimes
filewill return more than one line. Here’s what happens on my Mac:The
filecommand returns different output depending upon the OS. However, the wordexecutablewill be in executable programs, and usually the architecture will appear too.Compare the above to what I get on my Linux box:
And a Solaris box:
In all three, you’ll see the word
executableand the architecture (x86-64,i386, orSPARCwith32-bit).Addendum
Off the top of my head, you could do something like this in BASH:
Basically, I’m running the test, then if that is successful, I do a grep on the output of the
filecommand. Thegrep -qmeans don’t print any output, but use the exit code of grep to see if I found the string. If your system doesn’t takegrep -q, you can trygrep "regex" > /dev/null 2>&1.Again, the output of the
filecommand may vary from system to system, so you’ll have to verify that these will work on your system. Also, I’m checking the executable bit. If a file is a binary executable, but the executable bit isn’t on, I’ll say it’s not executable. This may not be what you want.