gpt4 book ai didi

linux - 使用exec命令时无法退出Shell脚本

转载 作者:行者123 更新时间:2023-12-03 08:19:28 26 4
gpt4 key购买 nike

我有一个主脚本(deploy_test.sh),该脚本使用find命令遍历文件并执行其他几个shell脚本。即使其他Shell遇到故障,主脚本也不会退出。我在脚本开始时使用了几个选项,但仍然无法退出,脚本一直持续到结束。

deploy_test.sh

#!/usr/bin/env bash
set -euo pipefail
shopt -s execfail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"


echo "Do you want to Continue: [Yes/No]"

read action

if [ $action = "Yes" ]
then


echo "Executing scripts"
find ${SCRIPT_DIR}/folder2 -type f -name '*.sh' -exec bash {} \;
echo $?
echo "This should also not be printed"


else
echo "nothing"
exit 1
fi


我的folder2有2个.sh文件(1.sh和2.sh)

1.sh(脚本末尾有一些特殊字符)
#!/usr/bin/env bash -eu

echo "hi iam in 1.sh and i have error in this file"
`

2.sh
#!/usr/bin/env bash -eu

echo "hi iam in 2.sh and i have no error in this file"

我执行脚本时的输出
(deploy) CSI-0048:test_test smullangi$ ./deploy_test.sh
Do you want to Continue: [Yes/No]
Yes
Executing scripts
hi iam in 1.sh and i have error in this file
/Users/smullangi/Desktop/test_test/folder2/1.sh: line 4: unexpected EOF while looking for matching ``'
/Users/smullangi/Desktop/test_test/folder2/1.sh: line 5: syntax error: unexpected end of file
hi iam in 2.sh and i have no error in this file
0
This should also not be printed

我希望在1.sh文件中遇到具有特殊字符的错误后退出此脚本。但是,无论我尝试过哪种选项,脚本在遇到错误后都不会退出。

任何帮助都非常感谢。我正在使用bash版本(3.2.57(1)-release)在macbook(macos catalina v10.15.3)上执行此操作

#UPDATE1:

我也觉得脚本根本没有执行。如果脚本中没有错误,那么它也会退出。简而言之,我感觉根据Phillippe的建议,在修改代码后,folder1/folder2中的脚本未得到执行
#!/usr/bin/env bash
set -euo pipefail
shopt -s execfail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"


echo "Do you want to Continue: [Yes/No]"

read action

if [ $action = "Yes" ]
then


echo "Executing scripts"
find ${SCRIPT_DIR}/folder2 -type f -name '*.sh' -exec false bash {} +
#find ${SCRIPT_DIR}/folder2 -type f -name '*.sh' -exec bash {} \;
echo $?
echo "This should also not be printed"


else
echo "nothing"
exit 1
fi

输出量
(deploy) CSI-0048:test_test smullangi$ ./deploy_test.sh 
Do you want to Continue: [Yes/No]
Yes
Executing scripts

最佳答案

find运行的命令给出错误时,并不总是以错误代码退出:

find ${SCRIPT_DIR}/folder1 -type f -exec false {} \;

上面的 find命令本身成功运行,即使它运行的每个命令都出错。

以下 find给出错误:
find ${SCRIPT_DIR}/folder1 -type f -exec false {} +

要对每个脚本进行错误处理,您可以执行
cd ${SCRIPT_DIR}/folder1
for script in ./*.sh; do
$script
done

关于linux - 使用exec命令时无法退出Shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61096187/

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