linux - 子 shell 命令失败时如何终止 shell?

标签 linux bash shell

如何在子 shell 命令失败时终止 shell。

例如:

check(){
  if [ $1 -eq $1 2> /dev/null ]; then
      echo "returning 0"
      return 0
  else
      echo "returning 1"
      return 1
  fi
}

if [ "($check $1)" == 1 ]; then
    echo "Error: with proper message"
    exit
fi

if [ "$1" -le 1000 ] || [ "$2" -ge 10000 ]; then
    echo "Error:"
    exit 
fi

我在这里传递一个字符串,首先是条件失败,其次是条件执行并在命令行“预期整数表达式”中出现错误。 我知道 () 子 shell 命令失败但 shell 没有终止。当子 shell 命令失败时如何退出 shell。

最佳答案

您想测试函数的退出状态。以下内容:

if [ "($check $1)" == 1 ]; then

可能会导致错误。即使你说:

if [ "$(check $1)" == 1 ]; then

不会比较退出状态,即函数的返回值。它会将函数的输出1进行比较。

您需要通过以下方式调用您的函数:

check $1

然后通过以下语句检查退出状态:

if [ $? -ne 0 ]; then
    echo "Error: with proper message"
    exit
fi

(据我所知,这里没有涉及任何子 shell。)

关于linux - 子 shell 命令失败时如何终止 shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546740/

相关文章:

linux - 从 Ubuntu 终端使用不同的命令行参数循环

linux - 系统重启后 systemctl 服务未启动

linux - ldap 用户的 nslcd 身份验证失败,错误为 "lookup failed: No results returned"

linux - Unix zip 命令正在更新现有存档而不是创建新存档

bash - awk 打印在 bash shell 脚本中不起作用

c++ - 跟踪 gcc 编译以及哪些代码减慢了它的速度

c# - 如何在 SUSE (Linux) 上运行控制台应用程序 Exe

linux - 获取linux中打开的应用程序窗口数

bash - shell脚本+数字总和

用字符在数字上填充 0 的 bash 脚本