bashenvironment-modules

Module files don't return non-zero exit codes to bash if the module fails to load. How can you make a conditional in bash with that?


I'm new here, so I apologize in advance if I'm not following the protocol, but the message said to ask a new question. I had asked an earlier question: How can a bash script try to load one module file and if that fails, load another?, but it is not a duplicate of Bash conditional based on exit code of command as marked.

The reason is that the module load does not return a non-zero exit code if it fails to load. These are the Environment Modules that I am trying to use.

For example,

#!/bin/bash

if module load fake_module; then
    echo "Should never have gotten here"
else
    echo "This is what I should see."
fi

results in

ModuleCmd_Load.c(213):ERROR:105: Unable to locate a modulefile for 'fake_module'
Should never have gotten here

How can I attempt to load fake_module and if that fails attempt to do something else? This is specifically in a bash script. Thank you!

Edit: I want to be clear that I don't have the ability to modify the module files directly.


Solution

  • Use the command output/error instead of its return value, and check for the keyword ERROR matches your output/error

    #!/bin/bash
    
    RES=$( { module load fake_module; } 2>&1 )
    if [[ "$RES" != *"ERROR"* ]]; then
        echo "Should never have gotten here"  # the command has no errors
    else
        echo "This is what I should see."   # the command has an error
    fi