9

I want to do some troubleshooting on my bash script. Is there a short and simple command that generates both stdout and stderr so that I can use 2>&1 on it? Sorry if this looks trivial, but I just can't think of one at the moment.

0

4 Answers 4

8

A simple approach would be to use ls to list actual and imaginary files:

ls . *.blah

This assumes that there are visible files in the working directory and that you don't have any files that end in .blah1


1. ...and if you do, we won't judge you.

1
  • 1
    That won't work in zsh, fish, csh, tcsh and bash -O failglob. (and ls . may return nothing on stdout if the current directory only has hidden files/dirs). Better ls / /x Commented Aug 13, 2014 at 7:02
7

Just write a subshell which sends to stdout and stderr...

(echo STDOUT && echo STDERR >&2) 

For proof that it works:

(echo STDOUT && echo STDERR >&2) > STDOUT.txt 2> STDERR.txt

This will create files STDOUT.txt and STDERR.txt containing the words STDOUT and STDERR respectively.

2
ls / /x
df / /x
wc / /etc/passwd
od / /dev/null

To guaranteed stdout written before stderr:

(w;/) # Bourne/csh like shells only.
sh -c 'w;/'
'time' w
1

You can write a function to use later:

gen_stdout_stderr() {                                                           
    printf "%s\n" "STDERR" >&2                                                  
    printf "%s\n" "STDOUT"                                                      
}

Then:

$ gen_stdout_stderr 
STDERR
STDOUT

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .