kosta
kosta

Reputation: 4750

Setting and using environment variable in docker alpine in the same line in shell

I want to set and use the environment variable in alpine shell in the following manner

docker run --rm -it alpine:latest /bin/sh -c MY_VAR=mytext;  echo $MY_VAR

However, it doesn't print out anything. How do I do this correctly?

EDIT

More, specifically it doesn't work inside the docker-compose like this

version: "3.7"
services: 
  tree:
    image: alpine:latest
    entrypoint: ["/bin/ash", "-c", "MY_VAR=mytext; echo ${MY_VAR}"]

docker-compose run tree gives me a blank string

Upvotes: 3

Views: 6502

Answers (2)

uzay95
uzay95

Reputation: 16642

I just wanted to put powershell command for setting and reading env var:

enter image description here

PS C:\> $SELAM=$(docker run -t --rm alpine echo "naber") ; docker run -t --rm -e SELAM=$SELAM alpine /bin/sh -c "echo abi $SELAM";

Upvotes: 0

anubhava
anubhava

Reputation: 785761

Use -e or --env option in docker run:

docker run --rm -it -e MY_VAR=mytext alpine:latest /bin/sh -c 'echo "$MY_VAR"'

mytext

It is important to quote the command line you're using for the container.

Even this should print correct value of variable MY_VAR:

docker run --rm -it alpine:latest /bin/sh -c 'MY_VAR=mytext; echo "$MY_VAR"'

For the second part of docker-compose use this docker-compose.yml with environment section and print it with double $$:

version: "3.7"
services:
  tree:
    environment:
      - MY_VAR=mytext
    image: alpine:latest
    container_name: alpine
    entrypoint:
      - /bin/ash
      - -c
      - 'echo $$MY_VAR'

And check output with:

docker-compose -f docker-compose.yml up

Recreating alpine ... done
Attaching to alpine
alpine  | mytext
alpine exited with code 0

Upvotes: 3

Related Questions