简体   繁体   中英

zsh function to set docker environment on OSX

I am trying to create a function in zsh to run the command docker-machine env <machine> for the current machine if there is only one machine running. I am trying to get it to run the following eval command:

eval "$(docker-machine env default)"

To set the docker environment variables, running docker-machine env default will output the following:

export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/Users/chris/.docker/machine/machines/default"
export DOCKER_MACHINE_NAME="default"
# Run this command to configure your shell:
# eval "$(docker-machine env default)"

So, to set the environment correctly, you need to enter eval "$(docker-machine env default)"

I have the following function

dmset() {
    COUNT=`docker-machine ls | grep "Running" | wc -l`
    if [[ "${COUNT// /}" == "1" ]]
    then
        RUNNING_MACHINE=`docker-machine ls | grep "Running" | awk '{print $1;}'`
        COMMAND="\"\$(docker-machine env $RUNNING_MACHINE)\""
        eval $COMMAND
        echo Setting docker environment for $RUNNING_MACHINE
    else
        echo "Unable to set Docker environment"
    fi
}

but this is not working. I get the following error message:

(eval):1: no such file or directory: export DOCKER_TLS_VERIFY="1"\nexport DOCKER_HOST="tcp://192.168.99.100:2376"\nexport DOCKER_CERT_PATH="/Users/chris/.docker/machine/machines/default"\nexport DOCKER_MACHINE_NAME="default"\n# Run this command to configure your shell: \n# eval "$(docker-machine env default)"

how can I run the eval command to set the environment via a single script?

Following @Etan Reisner's comment, I changed it to:

dmset() {
    COUNT=`docker-machine ls | grep "Running" | wc -l`
    if [[ "${COUNT// /}" == "1" ]]
    then
        RUNNING_MACHINE=`docker-machine ls | grep "Running" | awk '{print $1;}'`
        while IFS= read -r line
        do
            if [[ $line == 'export'* ]]
            then
                eval $line
            fi
        done < <(docker-machine env $RUNNING_MACHINE)
        echo "Docker environment set for $RUNNING_MACHINE"
    else
        echo "Unable to set Docker environment"
    fi
}

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