6

With cat I can read from a file to stdout. This way I can for example pipe a file out of a docker container:

docker exec my_container cat file > file_on_host

When I want to do the opposite, I would need a command that reads from stdin and saves to a file. Is there such a command?

docker exec my_container ??? file < file_on_host

4 Answers 4

7

tee can do that:

docker exec -i my_container tee file < file_on_host

The -i is necessary for stdin to work.

It will also output the file, which can be avoided by redirecting to the host's /dev/null:

docker exec -i my_container tee file < file_on_host > /dev/null
0
5

Similar to your approach,

docker exec -i my_container dd of=file < file_on_host

which gives you a nice status summary and doesn't write the data to stdout.

There are probably a few other options, e.g., cp /dev/stdin file (which might not work, depending on whether your container's OS supports /dev/stdin) and sh -c "cat > file".

1
  • Thank you for this solution! It's been running much faster than piping my content to the mongodb's shell running in the container! 🏎 Commented Aug 14, 2020 at 13:43
2

Actually seems to be easier with :

docker cp localfile.txt <CONTAINER ID>:/home/docker/data/

1
  • I'm sure when I wrote the question there was something preventing me from using docker cp, maybe the file_on_host was actually stdout of another process. But for copying actual files this is of course the easiest solution.
    – AndreKR
    Commented Nov 9, 2021 at 4:26
-1

I must not have understood the question, because you can either use plain old redirection like you did the first time

docker exec my_container < file_on_host > file

or use cat (again, with redirection).

3
  • That redirection happens between docker and file on the host. The > does not happen inside the container. If I wanted it to, it would involve quotes, which forces me to quote other quotes, so I don't like that solution.
    – AndreKR
    Commented Nov 11, 2016 at 17:08
  • I have no idea what a "container" is, or how it comes into play. Your question was "read from stdin and save to a file".
    – hymie
    Commented Nov 11, 2016 at 17:09
  • 4
    this is similar to the sudo redirection problem and has the same answer.
    – hildred
    Commented Nov 11, 2016 at 17:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .