Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

BUG: Shell builtin `which` prints non-existent commands to stdout



TL;DR: When `which` does not find a command it prints the error to standard output instead of standard error. Exit code is set correctly, though, and error messages about ‘bad options’ are sent to standard error as expected.

In a nutshell:

```sh
$ echo $SHELL              # can you tell us a little about yourself?
/usr/bin/zsh               # ✓
$ type which               # please tell us what you know about `which`
which is a shell builtin   # ✓
$ which vi                 # can you find `vi`?
/usr/bin/vi                # ✓
$ echo $?                  # show us the exit code
0                          # ✓
$ which nxcmd              # tell me about a non-existent command
nxcmd not found            # ✓
$ echo $?                  # and let us see the exit code
1                          # ✓
$ which nxcmd 2>/dev/null  # this command ought to keep `which` silent, but …
nxcmd not found            # ✗
$ which nxcmd >/dev/null   # … the error message is sent to stdout
$                          # ✗
$ which -T                 # let's try an unrecognized option
which: bad option: -T      # ✓
$ which -T 2>/dev/null     # redirect the same to stderr
$                          # ✓
```

Expected behaviour, as illustrated by GNU `which`:

```sh
$ /usr/bin/which --version | head -1
GNU which v2.21, Copyright (C) 1999 - 2015 Carlo Wood.
$ /usr/bin/which nxcmd 2>/dev/null
$ echo $?
1
```

Interim solution:

```sh
# ~/.zshrc
alias which='command which'
```

OS, architecture and zsh version:

```sh
$ uname -a
Linux nakamu 4.18.9 #1 SMP PREEMPT Wed Sep 19 21:19:17 UTC 2018 x86_64 GNU/Linux
$ echo $ZSH_VERSION
5.6.2
```

Cheers,

--
Klaus Alexander Seistrup
https://klaus.seistrup.dk/



Messages sorted by: Reverse Date, Date, Thread, Author