zsh函数在OSX上设置docker环境

时间:2015-12-29 19:03:28

标签: macos shell docker zsh

我正在尝试在zsh中创建一个函数,以便在只有一台机器运行的情况下为当前机器运行命令docker-machine env <machine>。我试图让它运行以下eval命令:

eval "$(docker-machine env default)"

要设置泊坞窗环境变量,运行docker-machine env default将输出以下内容:

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)"

因此,要正确设置环境,您需要输入eval "$(docker-machine env default)"

我有以下功能

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
}

但这不起作用。我收到以下错误消息:

(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)"

如何运行eval命令通过单个脚本设置环境?

1 个答案:

答案 0 :(得分:4)

根据@Etan Reisner的评论,我将其更改为:

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
}