0

I want pipe to cd by define a mycd function, expect using like this: echo workspace | mycd

this is how my function look like:

mycd(){
  read path
  cd $path && ls #The problem is (cd path) didn't get into the path, but (&& ls) is working good.
}

my test below shows that case 1 not able to change the path, but case 2 do.

1.
~ $ echo workspace | mycd
~ $ 

2.
~ $ mycd
workspace
~/workspace $

Ren Green
  • 11
  • 3
  • Pipe isn't always a valid solution for the problem. `read` [has it's quirks that you may not know about](https://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line), so your program will fail when you least expect it. Instead of piping you could use command substitution `cd $(someCommand)`. You could also use `PWD=$(...) command` for one-time command in pipe. – Tooster May 29 '21 at 12:32

2 Answers2

0

A bash function runs in a subshell and the path is changed in that process. That's why ls shows the contents of the directory. However, when the function exits you see that your original shell is still using the old path. See this question for more information.

You can accomplish what you want with an alias:

alias mycd='read path && cd "$path" && ls'
echo workspace | mycd
~/workspace $

Make sure you use single quotes, with double quotes the variable $path will get expanded (to nothing) when the alias is defined.

micke
  • 899
  • 9
  • 23
-2

read sets response into a variable, so your code should look like

mycd(){
  read path
  cd "$path" && ls
}

After that your code will work, i hope i helped