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.

find --version
if [[ $? == 127 ]]
    exit 1

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.

|improve this answer|||||

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.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.