使用 exec 命令时无法退出 shell 脚本

Unable to exit shell script when using exec command

我有一个主脚本 (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

我的文件夹 2 有 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 具有特殊字符的文件中遇到错误后退出。但是无论我尝试过什么选项,脚本在遇到错误后都不会退出。

非常感谢您的帮助。我在 macbook (macos catalina v10.15.3) 上执行此操作 bash version(3.2.57(1)-release)

#UPDATE1:

另外我觉得脚本根本没有执行。如果脚本中没有错误,那么它也会退出。简而言之,我觉得我在 folder1/folder2 中的脚本没有按照 Phillippe 的建议

修改代码后执行
#!/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

我没有找到任何使用 exec 的优雅解决方案。所以我在 find 命令中使用了 xargs,它工作得很好。 Shell 退出并显示相应的错误消息。我用这个作为参考 https://unix.stackexchange.com/questions/571215/force-xargs-to-stop-on-first-command-error

#!/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' | xargs -I {} sh -c 'bash "" || exit 255' sh {}
 echo $?
 echo "This should also not be printed"


else
echo "nothing"
exit 1
fi