如果模块加载失败,模块文件不会 return 非零退出代码到 bash。你怎么能用它在 bash 中做一个条件?

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?

我是新来的,所以如果我不遵守协议,我提前道歉,但是消息说要问一个新问题。我之前问过一个问题:How can a bash script try to load one module file and if that fails, load another?, but it is not a duplicate of as marked.

原因是模块加载在加载失败时不会return非零退出代码。这些是我正在尝试使用的 Environment Modules

例如,

#!/bin/bash

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

结果

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

我如何尝试加载 fake_module 并且如果失败尝试做其他事情?这具体是在 bash 脚本中。谢谢!

编辑:我想明确一点,我没有能力直接修改模块文件。

使用命令 output/error 而不是其 return 值,并检查关键字 ERROR 与您的 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

旧版本的模块,如您使用的 3.2 版本,总是 return 0 无论是失败还是成功。使用此版本,您必须按照@franzisk 的建议解析输出。模块 return 其在 stderr 上的输出(因为 stdout 用于捕获要应用的环境更改)

如果你不想依赖错误信息,你可以在module load命令后用module list命令列出加载的模块。如果在 module list 命令输出中未找到模块,则表示模块加载尝试失败。

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

较新版本的模块 (>= 4.0) 现在 return 一个适当的退出代码。因此,您的初始示例将适用于这些较新的版本。