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:

  • dotnet core on docker performance
  • docker is great for run-anywhere but what about the machines to host docker?
  • Using Kubernetes or Apache mesos
  • Hide/obfuscate environmental parameters in docker
  • docker compose: create two containers from one image
  • docker mapping volume directory not showing up [closed]
  • 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

  • How can I run Win32OLE calls from ubuntu?
  • How to run protractor on docker?
  • How to specify docker image's DNS?
  • https is not working on httpd docker container
  • What are advantages of writing script file in Docker?
  • Docker db container running. Another process with pid <id> is using unix socket file
  • 2 Solutions collect form web for “Write to a file on docker container gives error: No such file or directory”

    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
    

    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.

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.