简体   繁体   中英

How to use “>>” operator in Docker?

I'm trying to append a string to a file in a docker container using docker exec . However, it doesn't seem to interpret properly the ">>" operator

 sudo docker exec --interactive mycontainer cat /etc/postfix/main.cf

returns

smtpd_banner = $myhostname ESMTP $mail_name (Debian)
biff = no
append_dot_mydomain = no
readme_directory = no

# Basic configuration
# myhostname =
...

But

sudo docker exec --interactive mycontainer echo "my new line" >> /etc/postfix/main.cf

returns -bash: /etc/postfix/main.cf: No such file or directory

Either way there is a trick to pass in the ">>" operator to docker-exec, or there is another command to append a string to a file (which would be OK aswell, but I couldn't find one that is native, because containers do not have any fancy librairies).

Has anyone a trick ?

You're running the sudo command in a shell, and it is interpreting the >> before it ever reaches sudo or the docker client. You need to escape or quote the characters so your own shell doesn't interpret them, and then you need to run a shell inside the docker container to interpret them:

sudo docker exec -i mycontainer \
  /bin/sh -c 'echo "my new line" >> /etc/postfix/main.cf'

To pass variables from the outer shell to inside the container, you won't be able to use single quotes. You can use double quotes and escape anything you want to pass to the inner shell.

sudo docker exec -i mycontainer \
  /bin/sh -c "echo \"$host_var \$container_var\" >> /etc/postfix/main.cf"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM