Here's the concrete task I'm trying to accomplish. zsh behaves the way I like
$ zsh
$ which clang > /dev/null 2&>1 && echo clang || echo gcc
clang
$ which doesntexist > /dev/null 2&>1 && echo doesntexist || echo gcc
gcc
But, in bash:
$ bash
$ which clang > /dev/null 2&>1 && echo clang || echo gcc
gcc
Here's the general case:
$ which clang > /dev/null 2&>1; echo $?
1
$ which clang; echo $?
/usr/bin/clang
0
There's something wrong with how I'm redirecting output. What's the right way?
Use this:
Also you can use this:
This works because in
[[ ]]
empty strings are falsey.You're using zsh's
&>
operator, which redirects stderr and stdout. The way you've used it suggests you meant... > /dev/null 2>&1
instead.I would do this as:
I think you're redirecting the wrong way:
Should be
It's probably how either shells allow the former method. In bash it's not the right way. Bash would interpret it instead like:
In which
2
is added as an argument.You can verify that by creating a function like
And call it as:
And you would get
1 2
in e.log.In bash it's also simpler if you call your command like this:
Also rather than calling an external binary like
which
, usetype -P
instead. No need to redirect stderr output too.