0

I have written this little script to find executables that are passed as arguments e.g.

./testexec du ls md 

How do I get the script to not output commands that are not found - e.g. not to display error output for "md" command ??

  #!/bin/sh

    for filename in "$@"
    do
    which $filename
    done
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
frodo
  • 1,053
  • 5
  • 17
  • 33

2 Answers2

6

If you are using bash, you should use the builtin "type" rather than the external utility "which". The type command will return a non-zero exit status if the command is not found, which makes it easy to use with a conditional.

for filename in "$@"; do
   if type -P "$filename" >/dev/null; then
       echo "found in PATH: $filename"
   fi
done
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • 1
    @frodo: You can also capture the location of the executable like this: `for filename in "$@"; do if dir=$(type -P "$filename"); then echo "found in PATH: $dir"; fi; done` – Dennis Williamson Dec 06 '11 at 17:14
3

Just redirect the error message (coming from stderr) into /dev/null:

which $filename 2>/dev/null
eduffy
  • 39,140
  • 13
  • 95
  • 92
  • Thank you eduffy - I take it this means the "2" means "standard error " so any errors will be sent to /dev/null ? - apologies for the basic newbie question – frodo Dec 06 '11 at 15:05
  • 1
    Yes, "2" is stderr. Processes in *NIX start with 3 file descriptors: `0 - stdin 1 - stdout 2 - stderr ` – jordanm Dec 06 '11 at 16:00