Evaluate bash expression inside container, not host, when using docker exec

Viewed 1010

I am currently trying to run this command from my docker host:

docker exec container_name /bin/bash -c "touch .env; APP_KEY=$(php artisan key:generate | grep -o '\[.*]' | sed 's/[][]//g');"

Problem is that the expression $(expression) will be evaluated by the host, where php is not in the path, like it should be.

How do I tell docker that it should use container shell to evaluate the expression in the container? Or is there maybe another workaround to accomplish this?

2 Answers

You'll need to either quote the string in a way to avoid expansion (single quotes), which means you'll also need to escape any nested single quotes and other escape charactes:

docker exec container_name /bin/bash -c \
  'touch .env; APP_KEY=$(php artisan key:generate | grep -o \'\\\[.*]' | sed \'s\\/[][]//g\');'

or escape any shell characters (like the dollar):

docker exec container_name /bin/bash -c \
  "touch .env; APP_KEY=\$(php artisan key:generate | grep -o '\[.*]' | sed 's/[][]//g');"

The solution is to use single quotes rather than double quotes:

docker exec container_name /bin/bash -c 'touch .env; APP_KEY=$(php artisan key:generate | grep -o '\[.*]' | sed 's/[][]//g');'

In this case, $ expressions won't be expanded in the host command.

Related