如何从花括号中退出bash shell脚本?

时间:2017-01-11 23:58:12

标签: bash shell exit

我需要在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
    >

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

1 个答案:

答案 0 :(得分:5)

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

相关问题