Search code examples
bashubuntupipepiping

How to output bash command to stdout and pipe to another command at the same time?


I'm working on a server and to show detailed GPU information I use these commands:

nvidia-smi
ps -up `nvidia-smi |tail -n +16 | head -n -1 | sed 's/\s\s*/ /g' | cut -d' ' -f3` 

However as you can see, nvidia-smi is called twice. How can I make the output of nvidia-smi go to output and pipe to another command at the same time?


Solution

  • Use tee:

    ps -up `nvidia-smi |tee /dev/stderr |tail -n +16 | head -n -1 | sed 's/\s\s*/ /g' | cut -d' ' -f3` 
    

    Since stdout is piped, you can't make a copy to it, so I picked stderr to show output.

    If /dev/stderr is not available, use /proc/self/fd/2.