I am writing a script to create the source environment. Handling the PATH part is easy. Though how should I check if a program can be executed correctly when its path is added into PATH? Using which
is not sufficient as it's only check the existence of the executable, not running it. What I got now is to check the version of the program (i.e. find -version
) and check if the return message contains "command not found
". It's not ideal. Is there a better way to do this?
I don't think there is an ideal way to do what you want. As Martin says you can check that the executable bit is set but that won't confirm that it will actually run.
One thing that you can do is try and run the program and instead of looking for specific text from the program itself, look at the
$?
variable. This returns the exit status of the program (conventionally 0 for OK) or (on a CentoOS system I have to hand) 127 for file not found e.g.The reason there is no ideal way is that an exit status of 0 for OK is only conventional and programs may return different exit status if they run but encounter an error. This may work for you until something runs and returns an exit status of 127 to indicate some error condition.
You can use the
-x
operator to test if the executable flag is set on a file. It doesn't tell you if the executable will actually run though.