1

I am trying to do a more complicated task inside a running lxc ubuntu container, but my problem can be explained using this simple example. When I run

sudo lxc-attach -n container1 -- echo "test" > test.txt

inside of a shell script, I expect to find test.txt inside of my container, but instead I find it on my host machine! What has gone wrong?

3
  • 2
    The output redirection happens on the host machine. Have you tried sudo lxc-attach -n container1 -- 'echo "test" > test.txt'?
    – Hermann
    Feb 16, 2021 at 1:02
  • 1
    @Hermann is correct. More details of what happens here: The shell detects the redirection character >. It creates test.txt (or empties it, if it exists), and only then does it launch the sudo command, whose output it connects to test.txt. Feb 16, 2021 at 1:11
  • I tried that @Hermann and got a "No such file or directory - Failed to exec" message from lxc_attach_run_command . However, I did figure out what was wrong and I'll add it as an answer here. Feb 16, 2021 at 2:32

1 Answer 1

0

After some playing around I figured out the issue. I'll leave my question and answer here for the poor soul who inevitably runs into the same problem in the future and finds this question.

The key is to only attach to the container when accessing the file, not before running the whole command. Counterintuitively, the shell does not first connect into the container and execute the command, but rather interprets the > and creates a file locally first. To get around this, we use tee to connect to the container only when we need to. The solution is below.

echo "test" | sudo lxc-attach container1 -- tee test.txt

You must log in to answer this question.

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