dockerdocker-composealpine-linux

while-read not working int alpine docker image?


I'm trying to read a file content into variables inside an alpine image. But even reading plane lines and printing them does not work:

  echo:
    image: alpine:latest
    command: |
      sh -c '
        echo "info\n" | while read -r line; do
          printf "text around $line"
        done
      '

docker compose up echo always results in empty console, nothing is printed. Why?


Solution

  • The $line is being interpreted by docker compose and not the shell inside the container. To escape that from compose, use a second $, e.g.:

    services:
      echo:
        image: alpine:latest
        command: |
          sh -c '
            echo "info\n" | while read -r line; do
              printf "text around $$line"
            done
          '
    
    $ docker compose up
    [+] Running 1/1
     ✔ Container test-echo-1  Recreated                                                                 0.1s
    Attaching to echo-1
    echo-1  | text around info
    echo-1 exited with code 0
    

    For more details on how compose expands variables, see https://docs.docker.com/reference/compose-file/interpolation/