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.

  • 1
    ls . *blah (assuming you have some visible files in the current directory and don't have one ending in blah)... – jasonwryan Aug 13 '14 at 2:55
  • @jasonwryan, great! That works. Would you mind putting it down as answer? – Question Overflow Aug 13 '14 at 3:03

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
    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 – Stéphane Chazelas Aug 13 '14 at 7:02

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.

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

You can write a function to use later:

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


$ gen_stdout_stderr 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.