Servidores

tee y sustitución de procesos en bash: el código de salida que se pierde, tee -p que no termina y el orden de 2> >(tee) en 3 ejecuciones, medido con bash 5.2

Publicado el 3 de diciembre de 2026Última revisión: 3 de diciembre de 202612 min de lectura

Resultado de la prueba

`false | tee f` terminó con `$?` = 0 y `PIPESTATUS` = `1 0`; con `set -o pipefail` dio 1, y con `set -eo pipefail` el script paró. `cat f | tee f` dejó el fichero en 0 bytes en 2, 9 y 4 de 20 intentos (15 de 60) y intacto en el resto; `cat f | tee -a f` con 14 bytes dio 28 en 30 de 30. `exec > >(tee log)` entregó las 5 líneas siempre, pero con un consumidor lento (`sleep 0.5; cat`) el fichero no existía cuando bash volvió (3 de 3) y apareció 1 s después. `wait` sin argumentos y `wait $!` esperaron 1 s a una sustitución de procesos en bash 5.2, y `wait $!` devolvió su código (7). Con `2> >(tee err >&2)` y la salida de ambos flujos en un mismo fichero, el orden se alteró: en la prueba de 3 líneas, 234 a 282 de cada 300 salieron como o1 o2 e1 en lugar de o1 e1 o2 (9 tandas); salvo 15 de 300 en una tanda, nunca faltó ninguna línea al volver el script. `diff <(false) <(true)` dio 0, `diff <(cat inexistente) <(cat inexistente)` dio 0 con `set -eo pipefail`, y la copia con fichero temporal sí detectó el fallo de `sort` (exit 2). `yes | head -1` dio `PIPESTATUS` = `141 0`; `yes | tee f | head -1` dio `141 141 0` y paró; con `tee -p` y con `tee --output-error=warn` el pipeline seguía en marcha al cabo de 1 s (matado con `timeout`), y con `--output-error=exit` terminó con `141 1 0`. No se probó en una terminal con prompt, ni zsh, dash o ksh, ni otras versiones de bash o coreutils.

Contenido

Este artículo no contiene enlaces de afiliado.

comando | tee copia.log es la forma habitual de guardar el registro de un script de copia sin dejar de verlo, y diff <(sort a) <(sort b) la de comparar sin ficheros temporales. Ambas tienen trampas que se notan en cron y no en la consola. Aquí se mide cada una: qué código de salida llega, qué pasa si tee lee el mismo fichero que escribe, en qué orden y cuándo llega la salida con > >(tee log) y 2> >(tee err >&2), qué ve un script cuando falla el comando dentro de <(...) y cómo se comporta tee con SIGPIPE. Las trampas vecinas están medidas en set -e y pipefail en scripts de copia, redirecciones que truncan su propia entrada y comm y sort con LC_ALL; para limpiar los ficheros temporales al salir, véase mktemp y trap.

Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle aarch64, bash 5.2.21(1), tee de GNU coreutils 9.4, sin terminal interactiva (la salida va a ficheros y a tuberías, con LC_ALL=C). Todo se ejecuta en un directorio temporal que se borra al salir. El script test-tee-process-substitution-pipestatus.sh se ejecutó 3 veces. Las partes sin carreras ([1], [2], [4] salvo lo indicado, [6]) salieron iguales en las 3, pero las demás variaron y se informa del rango: cat f | tee f (cuántas veces vació el fichero), el orden con 2> >(tee), una tanda con 15 líneas incompletas y los bytes que llegó a escribir tee antes de morir por SIGPIPE (8192, 65536 o 73728). Los bucles que podrían no terminar (yes | tee ...) llevan timeout 1. No se probó en una terminal real (el "después del prompt" se simuló con un fichero que se comprueba nada más volver bash), en zsh, dash, ksh ni busybox, con otras versiones de bash o de coreutils, con ficheros grandes en cat f | tee -a f (solo 14 bytes), ni con tee en sistemas que no sean GNU. El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.

Salida de la ejecución 1

En las ejecuciones 2 y 3 coincide todo salvo las partes con carreras: los 20 tamaños de cat f | tee f, las líneas del apartado [5] y los bytes escritos en [7].

PRETTY_NAME="Ubuntu 24.04.5 LTS"; kernel: Linux 7.0.0-1017-oracle; bash 5.2.21(1)-release; tee (GNU coreutils) 9.4
[1] exit status of 'cmd | tee file'
  plain: $?=0 PIPESTATUS=1 0
  pipefail: $?=1 PIPESTATUS=1 0
  set -e only: script went on
  (exit 0)
  (exit 1)
  PIPESTATUS saved on the next line: 1
  PIPESTATUS after another command: 0
  pipefail takes the rightmost failure: 5
  tee file when cmd fails midway:
    status 4, file: partial|
[2] tee vs tee -a
  tee:    new|
  tee -a: old|new|
  tee into missing dir: exit 1, stderr: tee: nosuchdir/x.log: No such file or directory
  tee into mode-400 file (uid 10002): exit 1, stderr: tee: ro.log: Permission denied
  same, other output still written: new
[3] tee to a file that the same pipeline reads
  cat f | tee f x20 (file was 14 bytes), sizes after:
    14 14 0 14 14 14 14 14 14 0 14 14 14 14 14 14 14 14 14 14
28 28 28 28 28 28 28 28 28 28   <- sizes after 'cat f | tee -a f' x10 (small file; clean doubling would be 28)
  sort f | tee f: size after = 0
  sort -o f f: a|b|
  tee to other file + mv: a|b|
[4] exec > >(tee log): is the output complete when the script ends?
  run 1: tee log lines=5 stdout lines=5
  run 2: tee log lines=5 stdout lines=5
  run 3: tee log lines=5 stdout lines=5
  slow consumer (tee piped into 'sleep 0.5; cat'), is the file there when the script returns?
  run 1: file already there when bash returned: no
    1 s later: 6 bytes
  run 2: file already there when bash returned: no
    1 s later: 6 bytes
  run 3: file already there when bash returned: no
    1 s later: 6 bytes
  same, but piped to cat (the pipe stays open until the substitution closes it):
    hi
    pipe stayed open for 1s
  wait in bash 5.2:
    bare wait: 1s, file: w1.txt
    wait $!: 1s, file: done
    close fd then wait $!: 1s, file: done
    wait $! on a substitution that exits 7: returned 7
    without wait: exit status of the script is the status of echo, 0
[5] 2> >(tee err >&2): order of stdout/stderr (both end up in one file)
  run 1: plain 2>&1 alternating=yes; with tee: lines=200, alternating=no, first e line at line 4, last o line at line 181, err log lines=100
  run 2: plain 2>&1 alternating=yes; with tee: lines=200, alternating=no, first e line at line 2, last o line at line 199, err log lines=100
  run 3: plain 2>&1 alternating=yes; with tee: lines=200, alternating=no, first e line at line 4, last o line at line 199, err log lines=100
  300 repeats of a 3-line script (o1, e1 on stderr, o2), tee on stderr:
    run 1: incomplete right after the script returned: 0/300; not in order o1 e1 o2 after 0.5 s: 277/300
      orders seen: 277 x[o1o2e1] 23 x[o1e1o2] 
    run 2: incomplete right after the script returned: 0/300; not in order o1 e1 o2 after 0.5 s: 282/300
      orders seen: 282 x[o1o2e1] 18 x[o1e1o2] 
    run 3: incomplete right after the script returned: 0/300; not in order o1 e1 o2 after 0.5 s: 278/300
      orders seen: 278 x[o1o2e1] 22 x[o1e1o2] 
[6] <(cmd) vs temp file
  diff <(sort) <(sort): exit 1 (1 = differ)
  diff <(false) <(true): exit 0 (the failure of 'false' is invisible)
  diff <(cat missing) l2: exit 1 (same as 'files differ'), stderr: cat: nosuch.txt: No such file or directory
  set -eo pipefail, both inputs missing: diff exit 0 = identical, script went on
  set -e, cat <(false): script went on (exit 0)
  set -e, x=$(cat <(false)): script went on
  path of a substitution: /dev/fd/63
a b <- comm -12 with temp files
a b <- comm -12 with <()
  comm with unsorted input:
    b
    comm: file 1 is not in sorted order
    comm: input is not in sorted order
    exit 1
  temp-file version that does check the status:
    sort failed, exit 2, and the script knows before diff runs
  tail -c 3 on a substitution vs a file:
    <()    d   e   f
    file    d   e   f
    type of the substitution fd: fifo
[7] SIGPIPE (every run that could loop forever is capped with timeout 1; yes writes endlessly)
y
  yes | head -1: PIPESTATUS=141 0
  with pipefail: $?=141
  yes | tee f | head -1: PIPESTATUS=141 141 0
    y1.log: 73728 bytes
  yes | tee -p f | head -1: still running after 1s, killed by timeout (124)
    y2.log: > 1 MB; stderr: 
  yes | tee --output-error=warn f | head -1: still running after 1s, killed by timeout (124)
    y2.log: > 1 MB; stderr: tee: 'standard output': Broken pipe
  yes | tee --output-error=exit f | head -1: finished, PIPESTATUS=141 1 0
    y2.log: 65536 bytes; stderr: tee: 'standard output': Broken pipe
  (timeout exit 124)
    y4.log: > 1 MB; stderr: 
  finite source (seq 1 3000000, 22888896 bytes):
    tee (no option): PIPESTATUS=141 141 0, log 73728 bytes
    tee -p: PIPESTATUS=0 0 0, log 22888896 bytes

Lo que se ve

cmd | tee devuelve el código de tee. false | tee o.log terminó con $? = 0, aunque PIPESTATUS era 1 0. Con solo set -e el script siguió, y con set -o pipefail el estado fue 1; set -eo pipefail sí paró el script. PIPESTATUS solo vale en la línea siguiente: tras otro comando mostró 0. Con pipefail el estado es el del último comando que falló ((exit 3) | (exit 5) | cat dio 5). Si el comando muere a mitad, tee ya ha escrito lo anterior: con ( echo partial; exit 4; echo never ) el estado fue 4 y el fichero contenía partial.

tee sobrescribe, tee -a añade, y los errores de apertura no paran la salida. tee a.log dejó new; tee -a a.log dejó old y new. Con un directorio inexistente o un fichero 400 (como usuario sin privilegios, uid 10002) tee salió con 1 y mensaje de Permission denied, pero siguió escribiendo en la salida estándar (new).

Leer y escribir el mismo fichero en una tubería es una carrera. cat f | tee f con un fichero de 14 bytes lo dejó en 0 bytes en 2 de 20, 9 de 20 y 4 de 20 intentos (15 de 60) y en 14 bytes el resto: depende de si cat lee antes de que tee abra y trunque. sort f | tee f dejó 0 bytes (sort espera al final de la entrada). cat f | tee -a f dio 28 bytes en 30 de 30 intentos, pero eso es con 14 bytes: con ficheros mayores no se probó. Funcionaron sort -o f f y escribir a otro fichero y luego mv.

Con exec > >(tee log) la salida llegó completa, pero el script no espera a tee. Las 5 líneas llegaron en las 3 pruebas rápidas. Con un consumidor lento (sleep 0.5; cat > s4b.log), el fichero no existía cuando bash devolvió el control (3 de 3) y tenía los 6 bytes un segundo después: en una terminal, esa salida llegaría después del prompt, aunque eso no se probó. Si la salida del script va a una tubería (| cat), la tubería se mantuvo abierta 1 s hasta que terminó la sustitución. En bash 5.2, wait sin argumentos tardó 1 s y el fichero existía después; wait $! también, y wait $! devolvió 7 cuando la sustitución terminó con exit 7. Sin wait, el código de salida del script fue el de echo (0): el fallo de la sustitución no se ve.

Con 2> >(tee err >&2) el orden entre stdout y stderr se pierde. Con ambos flujos en el mismo fichero, 2>&1 sin tee dio la alternancia exacta o1 e1 o2 e2... en 3 de 3 pruebas. Con tee en stderr no alternó nunca: en una tanda las 100 líneas de stderr salieron después de las 100 de stdout; en otras la primera línea e apareció en la 2 a la 5 y la última o en la 151 a la 199. En 9 tandas de 300 ejecuciones de un script de 3 líneas (echo o1; echo e1 >&2; echo o2), entre 234 y 282 salieron como o1 o2 e1 y entre 18 y 66 como o1 e1 o2. Cuando el script volvió, faltaba alguna línea en 15 de 300 en una sola tanda y en 0 de 300 en las otras 8, de modo que con una espera de 0,5 s siempre estuvo todo. El fichero de errores de tee tuvo siempre las 100 líneas.

<(cmd) no informa del fallo de cmd. diff <(false) <(true) dio 0; diff <(cat inexistente) <(cat l2) dio 1 (como "los ficheros difieren"); con ambas entradas inexistentes dio 0 ("idénticos") incluso con set -eo pipefail. set -e tampoco paró con cat <(false) ni con x=$(cat <(false)). Cada cat imprimió su error en stderr, pero nada lo trasladó al estado. Con ficheros temporales, sort nosuch.txt > t1 falló con exit 2 antes de llegar a diff. Sin fallos, comm -12 dio el mismo resultado (a b) con ficheros temporales y con <(), y comm con entrada sin ordenar avisó "file 1 is not in sorted order" y salió con 1. La sustitución es una ruta /dev/fd/63 de tipo FIFO; tail -c 3 funcionó con ella igual que con un fichero.

tee y SIGPIPE. yes | head -1 dio PIPESTATUS = 141 0 (141 = 128 + SIGPIPE) y con pipefail el estado fue 141. yes | tee f | head -1 dio 141 141 0 y terminó, con el fichero de 8192, 65536 o 73728 bytes según la ejecución. Con tee -p y con tee --output-error=warn no terminó: al cabo de 1 s timeout los mató (con warn, tee avisó de "Broken pipe" en stderr), y el fichero tenía más de 1 MB. Con --output-error=exit terminó con 141 1 0 y 65536 bytes. trap "" PIPE en el script tampoco terminó (timeout, fichero de más de 1 MB). Con una fuente finita (seq 1 3000000, 22888896 bytes), tee sin opciones dio 141 141 0 y escribió 73728 bytes; tee -p dio 0 0 0 y escribió los 22888896 bytes: tee -p sigue escribiendo el registro entero cuando el lector ya se fue, lo cual es útil, pero con una fuente infinita no termina.

Qué hacer con esto

Este artículo no contiene enlaces de afiliado.