简体   繁体   中英

eval $(docker-machine env default) not working in iterm startup script

I have a startup script for iterm that starts a docker vm if missing, and connects to it if it already exists.

iterm配置

iterm_startup.sh

#!/bin/bash

typeset cmnd="docker-machine ls --filter name='default' --filter state='stopped' | grep default"
typeset ret_code

echo "running startup script ===> ${cmnd}"
eval $cmnd
ret_code=$?

# If not 0, means docker vm has already started
if [ $ret_code != 0 ]; then
    eval $(docker-machine env default)
# If 0, means defai;t docker vm not yet started
elif [ $ret_code == 0 ]; then
    docker-machine start default
fi

When a docker machine exists, it goes into the block that runs eval $(docker-machine env default) . However, when I go to the terminal, it still hasn't connected to the docker vm. I have to manually run eval $(docker-machine env default) in the shell again.

Can someone help me understand why eval $(docker-machine env default) doesn't work as expected in a script? :)

From the settings you showed, it looks like you're asking iTerm to "type in" the path to your script and run it as the first thing when a new terminal window opens. When that happens the script runs as a subprocess. If you look at what docker-machine env prints out it's just a set of export shell commands, so now you stumble on the general rule that subprocesses can't affect their parents' environments.

The simple answer is to change the command to "source" your script so that it runs in the context of the terminal's shell. Try changing your "send text at start" to

. ~/scripts/iterm_startup.sh

Looking at your script, I suspect you could make it much simpler using docker-machine status , and I suspect you need to do the "eval" step even if the machine isn't running yet.

MACHINE=default
if [ $(docker-machine status "$MACHINE" 2>&1) != "Running" ]; then
  docker-machine start "$MACHINE"
fi
eval $(docker-machine env "$MACHINE")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM