-2

I have a shell script with the line

COMPRESS_OPTION=`which compress`

There is no compress utility installed in our server, hence it gives the error

which: no compress in (/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/oracle/bin)

on the screen. So I tried

COMPRESS_OPTION=`which compress 2>/dev/null`

Even then I am getting error on screen.

closed as too broad by G-Man, Timothy Martin, Jeff Schaller, Archemar, Satō Katsura Feb 22 '18 at 7:28

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    What error are you getting? – Tomasz Feb 21 '18 at 18:28
  • which compress 2>/dev/null returns nothing, as expected, when I test it. Maybe the error is coming from somewhere else in the script where COMPRESS_OPTION is expected to be a certain value. Also I need to know which error you are talking about. – rudib Feb 21 '18 at 18:39
  • No. I am getting this error which: no compress in (/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/oracle/bin) even if I redirect the error to /dev/null – sabarish jackson Feb 21 '18 at 18:42
  • What shell are you using? When I use which with a nonexistent command it doesn't print an error message. – Barmar Feb 21 '18 at 22:01
  • 1
    BTW, another option is to use command -v compress. This is the POSIX standard way to find out which binary will be executed if you run a command. type -path is commonly available but not POSIX standard. – cas Feb 22 '18 at 2:26
1

Don't use which, use the POSIX standard command -v. For example:

COMPRESS_OPTION="$(command -v compress)"
[ $? != 0 ] && echo "compress not found" || echo "compress is $COMPRESS_OPTION"

If you don't want to change all the instances of which in your script, add a function like the following near the start:

which() {
  local w status
  w="$(command -v "$1")"
  status=$?
  [ -n "$w" ] && echo "$w"
  return $status
}

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