Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

shell - How to silence output from docker commands

I have written a script to run some docker commands for me and I would like to silence the output from these commands. for example docker load, docker run or docker stop.

docker load does have a flag --quiet that seems like it should do what I want however when I try to use this it still prints out Loaded image: myimage. Even if this flag did work for me, not all docker commands have this flag available. I had tried to use redirection like docker run ... 2>&1 /dev/null however the redirection arguments are interpreted as commands arguments for the docker container and this seems to be the same for other docker commands as well, for example tar -Oxf myimage.img.tgz | docker load 2>&1 /dev/null assumes that the redirection are arguments and decides to print out the command usage.

question from:https://stackoverflow.com/questions/66052910/how-to-silence-output-from-docker-commands

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is mostly a shell question regarding standard descriptors (stdout, stderr) and redirections.

To achieve what you want, you should not write cmd 2>&1 /dev/null nor cmd 2>&1 >/dev/null but just write: cmd >/dev/null 2>&1

Mnemonics:

The intuition to easily think of this > syntax is:

  • >/dev/null can be read: STDOUT := /dev/null
  • 2>&1 can be read: STDERR := STDOUT

This way, the fact that 2>&1 must be placed afterwards becomes clear.

(As an aside, redirecting both stderr to stdout to a pipe is a bit different, and would be written in the following order: cmd1 2>&1 | cmd2)

Minimal complete example to test this:

$ cmd() { echo "stdout"; echo >&2 "stderr"; }

$ cmd 2>&1 >/dev/null  # does no work as intended
stderr

$ cmd >/dev/null 2>&1  # ok

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...