Throw away standard output and error

11,732

Solution 1

You can use command grouping:

{ ps -p "$proc" | fgrep "$proc";} >/dev/null 2>&1

or wrap pipe in subshell:

(ps -p "$proc" | fgrep "$proc") >/dev/null 2>&1

Solution 2

&> /dev/null throws away both stderr and stdout. Same answer as the others, just a few characters shorter.

Share:
11,732

Related videos on Youtube

Aashu
Author by

Aashu

I have worked in BigData and Machine Learning. Always attract towards new technology and Research.

Updated on September 18, 2022

Comments

  • Aashu
    Aashu over 1 year

    I have redircted my ouput using /dev/null in bash script but it is still throwing an error. Code is following

    ps -p $proc | fgrep $proc> /dev/null
    if [ $? -ne '0' ] ; then
    ......
    fi    
    

    below is error

    error: list of process IDs must follow -p
    
    Usage:
     ps [options]
    
     Try 'ps --help <simple|list|output|threads|misc|all>'
      or 'ps --help <s|l|o|t|m|a>'
     for additional help text.
    
    For more details see ps(1).
    Usage: fgrep [OPTION]... PATTERN [FILE]...
    Try 'fgrep --help' for more information.
    

    How can I suppress this error without affecting $? output?

    • Admin
      Admin almost 9 years
      Not really an answer to your question but I think you'd better check if $proc is empty before using it.
    • Admin
      Admin almost 9 years
      @Aashu; What are you trying to do in the first place? - If you ps for a PID using -p the grep seems unnecessary. - You can do (for example): ps -p "$pid" >/dev/null 2>&1 || echo error, or: if ps -p "$pid" >/dev/null 2>&1 ; then echo okay ; else echo error ; fi.
    • Admin
      Admin almost 9 years
      Are you testing for existence of the PID $proc? If so then use test -n "$proc" && kill -0 "$proc"
  • Aashu
    Aashu almost 9 years
    Still getting same error.
  • Bazi
    Bazi almost 9 years
    edited the answer @Aashu, try it now
  • Janis
    Janis almost 9 years
    You don't need a subshell if all you want is redirecting I/O; you can use command grouping: { ps -p "$proc" | fgrep "$proc" ;} >/dev/null 2>&1.
  • Aloha
    Aloha almost 9 years
    I never knew subshells exist. Now I know.
  • cuonglm
    cuonglm almost 9 years
    @Janis: Good point, forgot about it. Updated my answer. Thanks.