2010-05-17 6 views
7

Sagen wir, ich tun dies in einer Unix-ShellUnix-Shell, Exit-Code mit verrohrt Kind bekommen

$ some-script.sh | grep mytext 

$ echo $? 

Das gibt mir den Exit-Code von grep

aber wie kann ich den Exit-Code erhalten some-script.sh

EDIT

Es sei angenommen, dass der Rohrbetrieb unveränderlich ist. dh ich kann es nicht auseinander brechen und die beiden Befehle separat ausführen

Antwort

5

Es gibt mehrere Lösungen, es hängt davon ab, was genau Sie tun möchten.

Die einfachste und verständliche Art und Weise wäre die Ausgabe in eine Datei zu senden, dann es grep nach dem Exit-Code zu speichern:

tmpfile=$(mktemp) 
./some-script.sh > $tmpfile 
retval=$? 
grep mytext $tmpfile 
rm tmpfile 
+0

danke für die Antwort, siehe meine Bearbeitung – Mike

+3

ich sehe. Vielleicht ist das eine Lösung: 'tmpfile = $ (mktemp); (./some-script.sh; echo $?> $ tmpfile) | grep mytext; retval = $ (cat $ tmpfile) '. Das ist ziemlich dreckig, aber vielleicht hilft es. – watain

+0

dann bekommt grep die Ausgabe von echo $? > tmpfile' – Mike

2

Wenn Sie bash verwenden:

PIPESTATUS 
    An array variable (see Arrays) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command). 
+0

Ich benutze sh. Mein Kunde mag Bash nicht – Mike

3

Ein Trick aus der comp.unix.shell FAQ (# 13) wird erläutert, wie die Pipeline in der Bourne-Shell sollte helfen erreichen, was Sie wollen:

You need to use a trick to pass the exit codes to the main 
    shell. You can do it using a pipe(2). Instead of running 
    "cmd1", you run "cmd1; echo $?" and make sure $? makes it way 
    to the shell. 

    exec 3>&1 
    eval ` 
    # now, inside the `...`, fd4 goes to the pipe 
    # whose other end is read and passed to eval; 
    # fd1 is the normal standard output preserved 
    # the line before with exec 3>&1 
    exec 4>&1 >&3 3>&- 
    { 
     cmd1 4>&-; echo "ec1=$?;" >&4 
    } | { 
     cmd2 4>&-; echo "ec2=$?;" >&4 
    } | cmd3 
    echo "ec3=$?;" >&4 
2

Es gibt ein Dienstprogramm mit dem Namen mispipe, das Teil des moreutils Pakets ist.

Es tut genau das: mispipe some-script.sh 'grep mytext'

0

Erster Ansatz, temporarly Exit-Status in irgendeiner Datei speichern. Diese Ursache müssen Sie Subshell mit Klammern erstellen:

(your_script.sh.pl.others; echo $? >/tmp/myerr)|\ #subshell with exitcode saving 
grep sh #next piped commands 
exitcode=$(cat /tmp/myerr) #restore saved exitcode 
echo $exitcode #and print them 

einen anderen Ansatz von Randy präsentierte oben, simplier Code-Implementierung:

some-script.sh | grep mytext 
echo ${PIPESTATUS[0]} #print exitcode for first commands. tables are indexted from 0 

seine alle. beide arbeiten unter bash (ich weiß, bashizm). Viel Glück :) beide Ansätze nicht temporäre Pipe in physische Datei speichern, nur Exit-Code.

Verwandte Themen