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



我是新来的,所以如果我没有遵守协议,我提前道歉,但消息说要问一个新问题。我之前问过一个问题:bash脚本如何尝试加载一个模块文件,如果失败,则加载另一个?,但它不是基于所标记的命令的退出代码的Bash条件的副本。

原因是如果加载失败,模块加载不会返回非零退出代码。这些是我正在尝试使用的环境模块。

例如,

#!/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而不是其返回值,并检查关键字error是否与您的输出/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,无论失败还是成功,都会返回0。在这个版本中,您必须按照@franzisk的建议解析输出。模块在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(现在返回一个适当的退出代码。因此,您的初始示例将适用于这些较新版本。

最新更新