いちいち 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
オプションを使ってみたらうまく出来た。