unix shell, getting exit code with piped child

后端 未结 5 480
南旧
南旧 2021-01-18 07:21

Let\'s say I do this in a unix shell

$ some-script.sh | grep mytext

$ echo $?

this will give me the exit code of grep

5条回答
  •  悲&欢浪女
    2021-01-18 08:21

    A trick from the comp.unix.shell FAQ (#13) explains how using the pipeline in the Bourne shell should help accomplish what you want:

       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
    

提交回复
热议问题