ahajib
ahajib

Reputation: 13520

Write to a file on docker container gives error: No such file or directory

I am trying to execute the following command:

docker exec mydocker echo "hello" >> /usr/local/src/scores.txt

But it gives me the following error:

No such file or directory

But using the following command:

docker exec -it mydocker bash

I make sure that the file actually exists there. Is there something that I am missing here?

Thanks

Upvotes: 1

Views: 2591

Answers (2)

Nauraushaun
Nauraushaun

Reputation: 1673

There is a good reason for this: it's being interpreted as two commands.

The solution is as stacksonstacks posted - wrap your container commands in a single shell command:

    docker exec mydocker sh -c 'echo "hello" >> /usr/local/src/scores.txt'

But why is it happening?

The key is that you've used a bash operator. Similar to any time you run something like:

    echo one two >> file.txt

The ">>" operator doesn't get passed as an argument to echo (like "one" and "two" do). Instead it executes your echo command and appends its output to a file.

In this case, the ">>" operator is doing the same to your docker exec, and trying to output the results to /usr/local/src/scores.txt and reporting that the directory does not exist (on the host, not the container).

This means that if you ran:

    docker exec mydocker echo "hello" >> scores.txt

You'd find scores.txt on your host, containing "hello" - the output from the command run on the container. And as a final test try:

    docker exec cf65263ed353 hostname && hostname

You'll see it prints the container's hostname (its hash ID), followed by your own. The second command is run on the host.

Upvotes: 1

stacksonstacks
stacksonstacks

Reputation: 9331

Try wrapping the echo command in a command string:

docker exec mydocker sh -c 'echo "hello" >> /usr/local/src/scores.txt'

Verify file contents using:

docker exec mydocker cat /usr/local/src/scores.txt

Upvotes: 4

Related Questions