bash - 读取命令停止 bash 脚本的执行

标签 bash

我有一个 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,并且 read1 退出状态退出,因为输入中没有零字节,这会导致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/"

关于bash - 读取命令停止 bash 脚本的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73894364/

相关文章:

python - 有没有办法可以用 bash 而不是 cmd 进行编译?

regex - 纯 Bash 替换捕获组

bash - 为什么在此bash脚本中执行顺序相反?

linux - 在 shell Linux 中获取非 ASCII 字符

linux - 当第一个程序未在 BASH 中退出时使用 2 级管道的问题

bash - 制作一个带有参数的 Bash 别名?

git - 如何检查远程 git 存储库 URL 的有效性?

linux - 文件中包含整数的行数

python - 如何使用 Homebrew 软件在 Cassandra 上设置 super 用户帐户?

Python 子进程 - mps-Youtube