Home > Software design >  $PATH not updated when running docker exec sh -c
$PATH not updated when running docker exec sh -c

Time:09-05

I have the following script in a sh file running in the host:

printf '\n\n=== Installing asdf ...\n\n'
docker container exec "$CONTAINER_NAME" sh -c 'git clone https://github.com/asdf-vm/asdf.git /root/.asdf --branch v0.10.2'
docker container exec "$CONTAINER_NAME" sh -c 'echo ''. /root/.asdf/asdf.sh'' >> /root/.bashrc'
docker container exec "$CONTAINER_NAME" sh -c 'echo ''. /root/.asdf/completions/asdf.bash'' >> /root/.bashrc'

printf '\n\n=== Installing node/npm using asdf ...\n\n'
NODEJS_VERSION='17.9.0'
docker container exec "$CONTAINER_NAME" sh -c 'asdf plugin add nodejs'
docker container exec "$CONTAINER_NAME" sh -c "asdf install nodejs $NODEJS_VERSION"
docker container exec "$CONTAINER_NAME" sh -c "asdf global nodejs $NODEJS_VERSION"

When asdf plugin add nodejs line is executed I get the following error:

sh: 1: asdf: not found

The whole issue is happening because $PATH is not being updated after the installation of asdf. I tried:

  1. to reload .bashrc/.profile after installing asdf
docker container exec "$CONTAINER_NAME" sh -c '. /root/.bashrc'
  1. to restart the container:
docker "$CONTAINER_NAME" restart

The (not so) weird thing is when I get into the container I can use asdf because, as expected, $PATH contains the path to asdf folders.

Does anybody knows what I am missing here?

CodePudding user response:

Each exec runs a new process which loses all its settings when it terminates. You need to start a new Bash shell with the correct options to read .bashrc ... or just give up on trying to use its interactive features for noninteractive scripts, and instead put these commands in a script, and then simply run it.

docker container exec "$container_name" bash '
printf "%s\n" "=== Installing asdf ..."
git clone https://github.com/asdf-vm/asdf.git /root/.asdf --branch v0.10.2
. /root/.asdf/asdf.sh
# . /root/.asdf/completions/asdf.bash

printf "%s\n" "=== Installing node/npm using asdf ..."
nodejs_version="17.9.0"
asdf plugin add nodejs
asdf install nodejs "$nodejs_version"
asdf global nodejs "$nodejs_version"'

I could not bring myself to keep all the newlines in your diagnostic messages.

Tangentially see also Correct Bash and shell script variable capitalization which explains why I changed the variables with the container name and the Node version to lower case.

  • Related