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
  • 74,806
  • 15
  • 120
  • 127
frodo
  • 973
  • 4
  • 16
  • 31

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
  • 29,762
  • 6
  • 59
  • 72
  • 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
  • 37,790
  • 12
  • 92
  • 91
  • 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