出现异常时如何退出脚本?

时间:2018-11-19 13:33:12

标签: bash shell sh

我有下一个脚本kafka connect-standalone.sh脚本:

#!/bin/sh
# Licensed to the Apache Software Foundation (ASF)

set -e    

if [ $# -lt 1 ];
then
        echo "USAGE: $0 [-daemon] connect-standalone.properties"
        exit 1
fi

base_dir=$(dirname $0)

if [ "x$KAFKA_LOG4J_OPTS" = "x" ]; then
    export KAFKA_LOG4J_OPTS="-Dlog4j.configuration=file:$base_dir/../config/connect-log4j.properties"
fi

if [ "x$KAFKA_HEAP_OPTS" = "x" ]; then
  export KAFKA_HEAP_OPTS="-Xms256M -Xmx2G"
fi

EXTRA_ARGS=${EXTRA_ARGS-'-name connectStandalone'}

COMMAND=$1
case $COMMAND in
  -daemon)
    EXTRA_ARGS="-daemon "$EXTRA_ARGS
    shift
    ;;
  *)
    ;;
esac

exec $(dirname $0)/kafka-run-class.sh $EXTRA_ARGS org.apache.kafka.connect.cli.ConnectStandalone "$@"*

当我运行脚本并且mqtt服务器未运行时,它将打印下一个异常:ERROR [mqtt-kafka-123456789] Connection to Broker failed! (com.evokly.kafka.connect.mqtt.MqttSourceConnector:132),但是脚本没有退出,而是继续运行。

总要检测到此异常并在出现该异常时退出脚本吗?

2 个答案:

答案 0 :(得分:0)

看起来像是在发生错误后不会退出的脚本是kafka-run-class.sh。在完成kafka-run-class.sh之后,connect-standalone.sh脚本没有理由继续运行。您可能希望捕获输出并检查确切的错误消息,然后做出相应的反应。修改kafka-run-class.sh脚本以处理此错误,或者将以下内容添加到connect-standalone.sh:

OUTPUT=$(./kafka-run-class.sh)

if [ "$OUTPUT" == "ERROR [mqtt-kafka-123456789] Connection to Broker failed!" ]
then
    echo $OUTPUT" was an error"
else
    echo $OUTPUT" was fine"
fi

$(COMMAND)捕获kafka-run-class.sh的输出。 if语句检查该命令的输出是否与您要退出的错误相匹配。

答案 1 :(得分:0)

  

但是脚本没有退出

这意味着您需要对脚本输出进行解析。下面,我使用fifo作为进程和脚本之间的缓冲区。

# fifo creation
tmp=$(mktemp -u)
trap 'rm -rf "$tmp"' EXIT
mkfifo "$tmp" 

# we start the command that writes to our fifo
# the command process is started in background
# this is our precious child
(  
    $(dirname $0)/kafka-run-class.sh \
        $EXTRA_ARGS \
        org.apache.kafka.connect.cli.ConnectStandalone \
        "$@"*
) > "$tmp" &
# remember childs pid
child=$!

# this is "watcher" / "parent" process - it checks if the child behaves
# for each line the child outputs...
while IFS= read -r line; do
   # print the line as is on stdout
   printf "%s" "$line" 
   # ...we check if the line has the string ERROR in any way
   if 
       case "$line" in
       *ERROR*) true; ;;
       *) false; ;;
       esac
  then
      echo "Error command printed out error line $line" >&2
      # we kill our child
      kill "$child"
      # let's wait for our child to exit
      wait
      # let's exit ourselves.
      exit 1
  fi
done < "$tmp"
  1. 我猜发生错误时,命令的输出将输出ERRORcase在输出流中检查是否有错误。如果是,它将返回true状态,然后输入then ...;如果不是,它将返回false状态,因此将不会输入then ...case命令的返回状态等于最后执行的命令。另外,当您使用[[ "$kafka_run_class_output" =~ ERROR ]]命令进行bash> = 4时,可以[[
  2. kafka命令行参数末尾的"$@"*看起来非常可疑。
  3. 我只是杀了我的孩子,但是如果您的孩子在接收到TERM信号时表现不佳,请确保将其发送为SIGKILL。
  4. 您的脚本具有/ bin / sh shebang,而不是bash。如果您有bash,请使用bash数组将参数传递给其他脚本。最好先EXTRA_ARGS+=(-daemon $EXTRA_ARGS),然后再kafka-run-class.sh ... "${EXTRA_ARGS[@]}"