如何从大括号内退出 bash shell 脚本?

How to exit a bash shell script from within curly braces?

我需要在我的 shell 脚本中使用花括号对命令进行分组,这样我就可以将它们的输出定向到单独的日志文件,就像这样...

    >cat how-to-exit-script-from-within-curly-braces.sh 

{
  printf "%d\n" 1
  printf "%d\n" 2
} | tee a.log
{
  printf "%d\n" 3
  printf "%d\n" 4
} | tee b.log

    >./how-to-exit-script-from-within-curly-braces.sh 
1
2
3
4
    >cat a.log 
1
2
    >cat b.log 
3
4
    >

虽然我添加了花括号以方便日志记录,但我仍然希望脚本在花括号内调用 exit 命令时退出。

当然不是。它只退出花括号,然后像这样继续执行脚本的其余部分...

    >cat how-to-exit-script-from-within-curly-braces.sh 

{
  printf "%d\n" 1
  exit
  printf "%d\n" 2
} | tee a.log
{
  printf "%d\n" 3
  printf "%d\n" 4
} | tee b.log

    >./how-to-exit-script-from-within-curly-braces.sh 
1
3
4
    >cat a.log 
1
    >cat b.log 
3
4
    >

使退出代码非零并向脚本添加 "set -e" 似乎不起作用...

    >cat how-to-exit-script-from-within-curly-braces.sh 
set -e

{
  printf "%d\n" 1
  exit 1
  printf "%d\n" 2
} | tee a.log
{
  printf "%d\n" 3
  printf "%d\n" 4
} | tee b.log

    >./how-to-exit-script-from-within-curly-braces.sh 
1
3
4
    >cat a.log 
1
    >cat b.log 
3
4
    >

有没有办法强制脚本从大括号内退出?

exit和花括号没有问题:

{
  exit
}
echo "This will never run."

但是,exit 和管道存在问题,这就是您 运行 遇到的问题:

exit | exit
echo "Still alive"

在bash中默认情况下,管道中的每个阶段都在一个子shell中运行,并且exit只能退出该子shell。在您的情况下,您可以改用重定向和进程替换:

{
  printf "%d\n" 1
  exit 1
  printf "%d\n" 2
} > >(tee a.log)
echo "This will not run"

请注意,这是 bash 特定代码,在 sh 中不起作用(例如使用 #!/bin/shsh myscript 时)。您必须改用 bash