1

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.

Reid
  • 85
  • 8
  • What is that *module* command? I don't recognize it as a regular linux command. Does it belong to some specific app? – Matias Barrios Feb 20 '20 at 14:45
  • Yes, @MatiasBarrios, the `module` is from [Environment Modules](http://modules.sourceforge.net/), mentioned above the first code block. – Reid Feb 20 '20 at 15:07

2 Answers2

0

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
Francesco Gasparetto
  • 1,819
  • 16
  • 20
0

Old versions of Modules, like version 3.2 you use, always return 0 whether it has failed or it is successful. With this version you have to parse output as proposed by @franzisk. Modules returns its output on stderr (as stdout is used to trap environment changes to apply)

If you do not want to rely on error messages, you can list loaded modules after the module load command with module list command. If module is not found in module list command output it means module load attempt failed.

module load fake_module
if [[ "`module list -t 2>&1`" = *"fake_module"* ]]; 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

Newer versions of Modules (>= 4.0) now return an appropriate exit code. So your initial example will work this these newer versions.