gpt4 book ai didi

linux - 使用 heredoc 输入时 Bash 返回码错误处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:34 26 4
gpt4 key购买 nike

动机

我处于这样一种情况,我必须通过单个 bash 调用运行多个 bash 命令,而无法编写完整的脚本文件(用例:Passing multiple commands to a container in Kubernetes)。 common solution就是用;或者&&组合命令,比如:

bash -c " \
echo \"Hello World\" ; \
ls -la ; \
run_some_command "

在实践中,编写这样的 bash 脚本很容易出错,因为我经常忘记分号,从而导致细微的错误。

灵感来自 this question ,我尝试使用 heredoc 以更标准的样式编写脚本:

bash <<EOF
echo "Hello World"
ls -la
run_some_command
EOF

不幸的是,我注意到使用 heredoc 时退出代码错误处理有所不同。例如:

bash -c " \
run_non_existing_command ; \
echo $? "

输出(注意 $? 正确捕获了退出代码):

bash: run_non_existing_command: command not found
127

鉴于

bash <<EOF
run_non_existing_command
echo $?
EOF

输出(注意 $? 与标准脚本执行相比无法捕获退出代码):

bash: line 1: run_non_existing_command: command not found
0

为什么 heredoc 版本的行为不同?是否有可能以 heredoc 样式编写脚本并保持正常的退出代码处理?

最佳答案

Why is the heredoc version behaving differently?

因为 $? 在运行命令之前被扩展了。

下面会输出1,即false命令的退出状态:

false
bash <<EOF
run_non_existing_command
echo $?
EOF

原理和下面一样,都会打印5:

variable=5
bash <<EOF
variable="This is ignored"
echo $variable
EOF

Is it possible to write the script in the heredoc style and maintaining normal exit code handling?

如果你想在子 shell 中扩展 $?,那么:

bash <<EOF
run_non_existing_command
echo \$?
EOF

bash <<'EOF'
run_non_existing_command
echo $?
EOF

另请注意:

bash -c \
run_non_existing_command ;
echo $? ;

正好等于:

bash -c run_non_existing_command
echo $?

echo $? 没有在 bash -c 中执行。

关于linux - 使用 heredoc 输入时 Bash 返回码错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58393894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com