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.
4 Answers
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.
-
1That won't work in zsh, fish, csh, tcsh and
bash -O failglob. (andls .may return nothing on stdout if the current directory only has hidden files/dirs). Betterls / /xStéphane Chazelas– Stéphane Chazelas2014-08-13 07:02:01 +00:00Commented Aug 13, 2014 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"
}
Then:
$ gen_stdout_stderr
STDERR
STDOUT