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

1

1

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?

Limeade answered 24/5, 2018 at 4:39 Comment(0)
P
3

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.

Pseudonym answered 24/5, 2018 at 4:50 Comment(3)
I've tested this on the server, and it worked! Thank you very much! Although using /dev/stderr is a little bit weird... Does this command dump to an error log file or something ? I'm sorry I'm not very knowledgeable about BashLimeade
@DangManhTruong Every program has two default output file descriptors, the standard output and the standard error. Usually both are inherited from the parent process, and in your case, the shell, which has both connected to the terminal.Pseudonym
@DangManhTruong "Standard Error" is not any system error log file. It's just another standard output stream for programs.Pseudonym

© 2022 - 2024 — McMap. All rights reserved.