Search code examples
bashshellosx-yosemitecommand-substitution

Adding a script/command/alias that uses command substitution


I have a command that I want to be able to run, and I will normally run it when my Mac starts up. The way I was trying to do it was to create an alias in ~/.bash_profile:

alias b2dinit="boot2docker up && $(boot2docker shellinit) && boot2docker ssh 'sudo /etc/init.d/docker restart'"

The boot2docker shellinit outputs a few commands that need to be executed. For example:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/mkobit/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

The problem I am having is that when a new shell is opened, the $(boot2docker shellinit) is executed and the above export commands are also executed, or it fails if the boot2docker VM is not active.

What is the right way to go about organizing this (alias, script, etc.) and if using command substitution is the right approach?


Solution

  • Use single quotes around the alias to defer command substitution until alias execution time or escape the $ in the double quotes.

    This will mean switching to double quotes on the inner sudo command and/or dropping in and out of single quotes (you cannot escape single quotes inside single quotes).

    alias b2dinit="boot2docker up && \$(boot2docker shellinit) && boot2docker ssh 'sudo /etc/init.d/docker restart'"
    

    or

    alias b2dinit='boot2docker up && $(boot2docker shellinit) && boot2docker ssh "sudo /etc/init.d/docker restart"'
    

    or

    alias b2dinit='boot2docker up && $(boot2docker shellinit) && boot2docker ssh '\''sudo /etc/init.d/docker restart'\'