softshipper
softshipper

Reputation: 34099

How to write docker command with /bin/sh and assign result to variable?

I am trying to write a shell script that should start a docker container. I have a running example, but it uses /bin/bash:

#!/bin/bash

export NETWORK=jetty-svc-test
export IMAGE_TAG=jetty-test-app
export SVC_NAME=svc-test

clean_up() {
    docker stop $SVC_NAME
    docker network rm $NETWORK
}

docker network create $NETWORK
if [ $? -eq 1 ]; then
    exit 1
fi

docker build --tag $IMAGE_TAG .
if [ $? -eq 1 ]; then
    exit 1
fi

docker run -it --rm --name $SVC_NAME --network=$NETWORK -v $(pwd)/app:/app -d $IMAGE_TAG
if [ $? -eq 1 ]; then
    exit 1
fi
sleep 5

export RES=$(docker run --rm --network=$NETWORK curlimages/curl:7.71.1 http://$SVC_NAME:8080 | docker run --rm -i stedolan/jq .)
export HEALTH_CHECK=$(echo "$RES" | docker run --rm -i stedolan/jq -r .status)

if [ "$HEALTH_CHECK" != "I am healthy" ]; then
    clean_up
    exit 1
fi

clean_up

but I need it in #!/bin/sh. For instance, the statement export RES=$(.. does not work in #!/bin/sh.

I need to rewrite the script above, because https://hub.docker.com/layers/docker/library/docker/19.03.12/images/sha256-d208a88b6afa09430a2f4becbc8dbe10bfdaeb1703f9ff3707ca96e89358a8e4?context=explore only supports #!/bin/sh and I would like to run the script above inside the docker:dind container.

How to write docker command with /bin/sh and assign result to variable?

Upvotes: 0

Views: 3072

Answers (2)

tripleee
tripleee

Reputation: 189749

You seem to be asking how to rewrite

export variable=$(command)
export other="value"

and the answer for POSIX sh is simply

variable=$(command)
export variable

other="value"
export other

See also Where is “export var=value” not available? (on Unix / Linux Stack Exchange).

Upvotes: 4

Adiii
Adiii

Reputation: 60074

As mentioned in the comment, you can check the script again shellcheck, I am not going to address the issue in shell script, as a suggestion in comment should work, but I will just to create a custom image by extending docker:dind, which will have bash as well as other utility that you are trying pull docker image for jq etc,

By doing this approach you will save network bandwidth plus CPU time.

FROM docker:dind
RUN apk add --no-cache bash jq curl

Now run this docker:dind image instead of the offical image, your script will become something like

docker run -dit --rm --name $SVC_NAME -p 3000:3000 --network=$NETWORK  jetty-test-app:latest
if [ $? -eq 1 ]; then
    exit 1
fi
sleep 2

RES=$(curl localhost:3000/users | jq .)

export HEALTH_CHECK=$(echo "$RES" | jq .status)

if [ "$HEALTH_CHECK" != "I am healthy" ]; then
    clean_up
    exit 1
fi
clean_up

Upvotes: 0

Related Questions