5

I've been using docker for a while and there's a command I write each time I boot up my docker:

eval $(docker-machine env)

I know eval shouldn't be used unless necessary, but it's mentioned by the following:

docker-machine env outputs environment variables like this:

docker-machine env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://<some_ip>:<some_port>"
export DOCKER_CERT_PATH="/home/gableroux/.docker/machine/machines/default"
export DOCKER_MACHINE_NAME="default"
# Run this command to configure your shell: 
# eval $(docker-machine env)

eval grabs these and load them in my current session.

Now what if I'd like to have an alias like this:

alias dockereval="eval $(docker-machine env)"

Syntax is good, but the problem is when a dotfile (let's say .zshrc as an example), well the content of the $() is evaluated when registering the alias when you source that file.

which dockereval

Results in

dockerenv: aliased to eval

I tried a few things like:

alias dockereval="docker-machine env | eval"
alias dockereval="docker-machine env | /bin/bash"
alias dockereval="eval `docker-machine env`"

but none did work. 2nd one is probably because it's running in a different session, 3rd does the same as $() I guess

Is there an other way to load these environment variables with an alias?

  • 1
    Use single-ticks (') in your alias definition so that the subshell is created and parsed each time you execute it rather then when you define the alias. – DopeGhoti Jun 8 '16 at 18:50
  • An alternate solution would be to use a function instead of an alias. I now prefer this to alias as I keep syntax highlighting and can split those magic shortcuts into multiple lines. 🍻 – GabLeRoux Oct 19 '18 at 12:38
8

Enclose your alias in single quotes instead of double quotes.

alias dockereval='eval $(docker-machine env)'

Double quotes allow expansion of variable (in bash at least) while single quotes don't

  • you saved 1 minute form every terminal opens. +1 – Alupotha Dec 13 '18 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.