Bash script - redirect child script stderr to parent's stdout
Asked Answered
P

2

7

I'm sure I'm missing something simple, but I'm using an executive script to call a few utility scripts and I want to handle all of the output from the utilities via one pipe. My issue is the utilities use stderr to report error conditions, but I can't capture that for use in the parent script.

Parent Script:

#!/bin/bash
child 2>&1 >/dev/null

Child Script

#!/bin/bash
echo "Print"
echo "Error" 1>&2

What I expect is that the stderr of child (and all of it's commands) is redirected to stdout (hence no output), but when I execute parent I get Error echo'd to the terminal ("Print" is sent to /dev/null).

Pitre answered 24/10, 2013 at 17:17 Comment(0)
M
10

What's happening is that you're redirecting stderr to stdout's filehandle (perhaps /dev/stdout). Then you redirect stdout to /dev/null. However, stderr is still pointing to /dev/stdout.

To ignore all output, first redirect stdout, then redirect stderr to stdout

child >/dev/null 2>&1

Or, more simply since you're using bash specifically, redirect stdout and stderr together:

child &>/dev/null
Malacostracan answered 24/10, 2013 at 17:40 Comment(2)
Order of operations. Thanks, works great and I feel about as dumb as I thought I would.Pitre
Don't kick yourself, took me ages to grok that.Malacostracan
P
2

Not an answer to the OP's question, but in case someone else is struggling to figure out how to redirect a child process's output to the parent's stdout, here it is.

#!/bin/bash
child &>>/dev/stdout &

This does the trick and will even work when backgrounding the child task as shown.

Thanks go to @glenn jackman for being the first person in a day-long search for a solution to mention /dev/stdout in his answer.

Update

Upon further research, with this answer being particularly helpful, it seems there's a way of doing this that also preserves the parent's stderr:

#!/bin/bash
child 1>&1 2>&2 &
Pearson answered 26/5, 2022 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.