忽略 Bash 脚本中 Source 命令的失败

Vap*_*ant 4 python macos bash shell terminal

所以我知道有很多关于堆栈溢出的答案可以忽略 bash 脚本中的错误。不过,它们似乎都不适用于 source 命令。

我已经尝试过久经考验的 source ../bin/activate || true

set -e在运行命令之前尝试过设置

我试过了 source ../bin/activate 2>&1 /dev/null

set +e在运行命令之前尝试过设置。这也不起作用。

但是在这段代码的每次运行中,我都会收到

run.01: line 12: ../bin/activate: 没有那个文件或目录

这个问题的上下文是我正在创建一个运行一些 python 代码的简单 bash 脚本。指示用户如何创建特定的虚拟环境,如果他们正确设置,此行将自动激活它,否则,这应该忽略无法激活运行并在当前激活的任何环境中继续运行命令。

# Try virtual environment

source ../bin/activate || true

## Run.

code="../src-01/driver.v01.py"

## --------------------
graphInputFile="undirected_graph_01.inp"
graphType="undirected"
srcColId="0"
desColId="1"
degreeFind="2"
outFile="count.undirected.num.nodes.out"

python $code  -inpGraphFile $graphInputFile  -graphFormat $graphType  -colSrcId $srcColId -colDesId $desColId  -degreeFind $degreeFind  -output_file $outFile
Run Code Online (Sandbox Code Playgroud)

无论命令是否source ../bin/activate成功,python 命令都应该执行。我有点不明白为什么这些解决方案都不起作用,目前我假设在这种情况下source可能会做一些与正常命令不同的事情。

编辑:

#!/bin/bash -x按照要求将shebang添加到我的文件中,但这没有做任何事情。

这是我运行此脚本时的确切终端输出。

Lucas-Macbook:test-01 lucasmachi$ sh run.01
run.01: line 14: ../bin/activate: No such file or directory
Lucas-Macbook:test-01 lucasmachi$ 
Run Code Online (Sandbox Code Playgroud)

run.01bash 脚本的名称在哪里。

另外澄清一下,我展示的代码没有经过审查。这是整个脚本(除了现在顶部提到的shebang。)

小智 6

您可以在代码中添加验证,以在获取文件之前检查文件是否存在:

[[ -f "../bin/activate" ]] && source ../bin/activate
Run Code Online (Sandbox Code Playgroud)

如果路径文件存在,则在路径之前使用 -f 标志将返回 true,如果不存在,则返回 false。

bash if 语句的单行语法如下:

[[ Condition that returns true or false ]] && Exec if true 
Run Code Online (Sandbox Code Playgroud)


tha*_*guy 5

This is a bug in Bash versions before 4.0 (macOS is stuck on 3.2).

Given this script:

#!/bin/bash
set -e
echo "Running $BASH_VERSION"
source "does not exist" || true
echo "Continuing"
Run Code Online (Sandbox Code Playgroud)

Running on macOS will say:

macos$ ./myscript
Running 3.2.57(1)-release
./myscript: line 3: does not exist: No such file or directory
Run Code Online (Sandbox Code Playgroud)

While on a modern system with an updated bash version, you get the expected behavior:

debian$ ./myscript
Running 5.0.11(1)-release
./myscript: line 3: does not exist: No such file or directory
Continuing
Run Code Online (Sandbox Code Playgroud)

If you need to support macOS and Bash 3.2, run set +e first to disable errexit, and optionally re-enable it afterwards.