Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - redirect child script stderr to parent's stdout

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).

like image 328
Sam Avatar asked Mar 21 '23 22:03

Sam


1 Answers

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
like image 53
glenn jackman Avatar answered Mar 24 '23 11:03

glenn jackman