Bash – How is this script (open-switch/opx-build/scripts/opx_run) passing variables

bashdockershell-script

Like many bash questions, I'm 100% sure there is an answer but Googling them is challenging.

I'm trying to understand the following script:

#!/bin/bash

# available options
export OPX_GIT_TAG="${OPX_GIT_TAG:-no}"

# package distribution
export OPX_RELEASE="${OPX_RELEASE:-unstable}"
# currently tracked release
export DIST="${DIST:-stretch}"
export ARCH="${ARCH:-amd64}"

export CUSTOM_SOURCES="${CUSTOM_SOURCES:-}"

# docker image name
IMAGE="opxhub/build"
# docker image tag
VERSION="${VERSION:-latest}"

interactive="-i"
if [ -t 1 ]; then
  # STDOUT is attached to TTY
  interactive="-it"
fi

read -d '' opx_docker_command <<- EOF
docker run
  --rm
  --name ${USER}_$(basename $PWD)_$$
  --privileged
  -e LOCAL_UID=$(id -u ${USER})
  -e LOCAL_GID=$(id -g ${USER})
  -v ${PWD}:/mnt
  -v $HOME/.gitconfig:/home/opx/.gitconfig
  -v /etc/localtime:/etc/localtime:ro
  -e ARCH
  -e DIST
  -e OPX_RELEASE
  -e OPX_GIT_TAG
  -e CUSTOM_SOURCES
  ${interactive}
  ${IMAGE}:${VERSION}
EOF

if [[ $# -gt 0 ]]; then
  # run command directly
  # not using bash because tar fails to complete
  # root cause unknown (see opx_rel_pkgasm.py:tar_in)
  $opx_docker_command sh -l -c "$*"
else
  # launch interactive shell
  # using bash here because tar does not fail in an interactive shell
  $opx_docker_command bash -l
fi

I'm confused by how they are generating their docker-run command – the parts about ARCH, DIST, OPX_RELEASE, etc – specifically. Should those not be enclosed with ${}? If not how are these variables being passed?

Best Answer

If you look carefully, you will see that the use of these variables is in a -e option of the docker-run command. This option is used to make environment variables available to the container.

So here, the script is specifying the name of the environment variable that should be passed to the container, and not the value itself (for which, as you stated correctly, it would have needed dereferencing, as in $ARCH or ${ARCH}).

You can have a look at the docker documentation for further reading.

Related Question