Search code examples
macosbashechopipecd

How to cd to directory echo'd by script


I have a function mkapp() in my .bash_profile which creates a directory based on input and then outputs the path where the directory was created. An example: calling mkapp createddir would output, using echo, ~/projects/pub/createddir.

I'm trying to run a command like this mkapp createddir | cd which would cd to the created directory specified in the output. The reason I'm not cd'ing in the function, is because I don't always want to change dir after the command.

Currently when I try to add the pipe and cd, I get -bash: echo: write error: Broken pipe

What can I do to use the pipe correctly?


Solution

  • cd expects a command line argument.

    Use command substitution like this:

    cd $(mkapp createddir)
    

    pipe is used to pass stdout of left hand command to the stdin of right hand command.