gpt4 book ai didi

bash - 为什么我的 "exit"命令没有退出我的 Bash 脚本?

转载 作者:行者123 更新时间:2023-11-29 09:09:13 25 4
gpt4 key购买 nike

我有这个 Bash 脚本:

#!/bin/bash
set -x
function doSomething() {
callee
echo "It should not go to here!"
}

function callee() {
( echo "before" ) && (echo "This is callee" && exit 1 )
echo "why I can see this?"
}


doSomething

这是结果:

+ set -x
+ doSomething
+ callee
+ echo before
before
+ echo 'This is callee'
This is callee
+ exit 1
+ echo 'why I can see this?'
why I can see this?
+ echo 'It should not go to here!'
It should not go to here!

我看到命令 exit,但它没有退出脚本 – 为什么 exit 不起作用?

最佳答案

您正在从子 shell 内部调用 exit,因此这是正在退出的 shell。试试这个:

function callee() {
( echo "before" ) && { echo "This is callee" && exit 1; }
echo "why I can see this?"
}

然而,这将从任何名为 callee 的 shell 中退出。您可能希望使用 return 而不是 exit 从函数返回。

关于bash - 为什么我的 "exit"命令没有退出我的 Bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266057/

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