我有一个bash脚本,其中我使用READ命令将多行字符串存储到一个变量中,但是由于某些我仍然不明白的原因,它停止了脚本的执行,状态代码为1退出.

#!/usr/bin/env bash

# some setup code
# ...

read -r -d '' test_command <<EOF
CI_TIMEOUT_MINUTES=20 \
FOO=foo \
BAR=${bar} \
yarn test "path/to/tests/"
EOF

echo "test_command: ${test_command}"

if ! kubectl exec -it "$pod" -- /bin/sh -c "${test_command}"; then
# ...

当执行脚本时,它在read命令执行时以状态1退出,而不到达行echo "test_command: ${test_command}".

推荐答案

您设置了set -e,read退出,退出状态为1,因为输入中没有零字节,这会导致set -e终止脚本.


我建议不要将命令存储为字符串.将命令存储为函数,然后序列化为字符串.我会这样做:

test_command() {
   # Quotes!
   CI_TIMEOUT_MINUTES=20 \
   FOO=foo \
   BAR="${bar}" \
   yarn test "path/to/tests/"
}

# First pass test_command function as a string, then call that function.
... sh -c "$(declare -f test_command); test_command"
# or to nicely handle arguments.
... sh -c "$(declare -f test_command);"' "$@"' _ test_command "arg1" "arg2"
# Anyway, here sh seems like an overkill.
... env CI_TIMEOUT_MINUTES=20 FOO=foo BAR="${bar}" yarn test "path/to/tests/"

Linux相关问答推荐

创建守护进程时打开0,1,2描述符

无法下载Centos 7上的存储库的元数据

无法分析nasm中的单词

Git - 打印以不同编码混合的文件

Linux 'column' 实用程序的使用

ln命令报错target not a directory

从另一个文件中的大文件中查找行的最快方法

从 curl 命令输出中获取值

从 Ansible 中的 shell 命令输出中提取特定数据

在 Ansible 中使用 JSON 查询过滤数据以从 ansible_fact 中提取数据

我应该如何从非 root Debian Linux 守护进程登录?

如何使用 __attribute__((visibility("default")))?

对一个命令使用不同的 PHP 版本 CLI 可执行文件

如何将执行的shell命令的结果存储在python的变量中?

如何计算列的平均值

如何在 Bash 中对齐空格分隔表的列?

将 bash 脚本添加到路径

从核心转储中获取堆栈跟踪

以原子方式移动目录

Linux 上真的没有异步块 I/O 吗?