
Ich habe eine Befehlszeilen-App, die viele Informationen an stdout ausgibt.
Wie kann ich das Programm beenden, wenn stdout eine bestimmte Zeichenfolge enthält?
zB sowas wie:
my_program | terminate_if_contains ERROR
Der Grund dafür ist, dass das Programm von einem Drittanbieter geschrieben wurde und zahlreiche FEHLER an die Standardausgabe ausgibt. Ich möchte jedoch beim ersten Fehler anhalten, damit ich nicht warten muss, bis das Programm beendet ist.
Antwort1
Versuchen:
my_program | sed '/ERROR/q'
Dies druckt alles bis einschließlich der ersten Zeile, die enthält ERROR
. An diesem Punkt sed
wird beendet. Kurz darauf my_program
wird ein Signal für unterbrochene Pipes (SIGPIPE) empfangen, das die meisten Programme zum Stoppen bringt.
Antwort2
Hier ist meine schnelle Lösung für dieses Problem:
Anwendungsbeispiele:
$ watch_and_kill_if.sh ERROR my_program
beobachten_und_töten_wenn.sh
#!/usr/bin/env bash
function show_help()
{
IT=$(CAT <<EOF
usage: ERROR_STR YOUR_PROGRAM
e.g.
this will watch for the word ERROR coming from your long running program
ERROR my_long_running_program
EOF
)
echo "$IT"
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$2" ]
then
show_help
fi
ERR=$1
shift;
$* |
while IFS= read -r line
do
echo $line
if [[ $line == *"$ERR"* ]]
then
exit;
fi
done
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$2" ]
then
show_help
fi
ERR=$1
shift;
$* |
while IFS= read -r line
do
echo $line
if [[ $line == *"$ERR"* ]]
then
exit;
fi
done