LoginSignup
10
5

More than 3 years have passed since last update.

[小ネタ]docker exec でリダイレクトを使いたい

Last updated at Posted at 2019-01-30

いちいち docker execで bashや sh を実行してしてファイルを書くのが面倒だったのでワンライナーでやりたいが、リダイレクト(>>)がうまくいかなかった時のメモ。

結論

以下のようにすれば良い

$docker exec -it 8c6757b43173 /bin/sh -c "echo 'hi' >> /var/log/access.log"

よく見るとdocker execのページにも以下の記載があった。

COMMAND should be an executable, a chained or a quoted command will not work. Example: docker exec -ti my_container "echo a && echo b" will not work, but docker exec -ti my_container sh -c "echo a && echo b" will.

経緯

コンテナ内でファイルへの追記をする時に以下の手順を実施していたが、面倒だなと感じた。

$docker exec -it 8c6757b43173 /bin/sh
/ # echo 'hoge' >> /var/log/access.log
/ # exit

しかし以下は失敗

$docker exec -it 8c6757b43173 "echo 'hoge' >> /var/log/access.log"
OCI runtime exec failed: exec failed: container_linux.go:348: starting container process caused "exec: \"echo 'hoge' >> /var/log/access.log\": stat echo 'hoge' >> /var/log/access.log: no such file or directory": unknown

以下の記事を見つける。

Docker exec - Write text to file in container

By using a double-quoted string to pass to bash -c, you ensure that the current shell performs string interpolation first, whereas the container's bash instance then sees the expanded result as a literal, as part of the embedded single-quoted string.

なるほど。
ということで先頭に記載の通り -c オプションを使ってみたらうまく出来た。

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5