Affichage des articles dont le libellé est tee. Afficher tous les articles
Affichage des articles dont le libellé est tee. Afficher tous les articles

vendredi 24 avril 2015

get return value ($?) of a tee'd command in ksh

How to get the return value of "command1" if passed to a " | command2" , for example "| tee OUTFILE" :
 
 
    command1 | tee OUTFILE


 With recent shells, you can use the array storing this : bash is ${PIPESTATUS[x]} , zsh is $pipestatus[x] to get this value :
 
      command1 | tee OUTFILE
      echo ${PIPESTATUS[0]}

With older shells, this feature is not available, but you still can use posix features and play around with the file descriptors :
 
    exec 4>&1; RETVAL=$({ { command1 ; echo $? >&3 ; } | { tee $OUTFILE >&4; } } 3>&1); exec 4>&-

 
Explainations 
  1. Create a file descriptor fd4 and map it to STDOUT
  2. Fill the RETVAL value with the fork.
    1. fd4 is transmitted, but STDOUT and STDERR are recreated for the forked process so fd4 still exist and is available.
    2. create the fd3 and redirect it to STDOUT
    3. map 'tee' STDOUT to the previously created fd4 so that it gets printed to the terminal; 
    4. tee then forks the piped 'command1' which output value $? is sent to fd3 with 'echo $? >&3', and hence outputed in the RETVAL variable; 
  3. Eventually, close the fd4


References :