using xargs to cd to a directory

Feeling like an idiot right now. Why does this not work?

echo "/some/directory/path" | xargs -n1 cd

Solution 1:

The pipe runs xargs in a subprocess, and xargs runs cd in a subprocess. Changes in a subprocess do not get propagated to the parent process.

Solution 2:

The command cd is a built-in because the information about the current directory is tied to a process and only shell built-in can change current directory of the running shell.

There are two problems with your code:

  1. xargs cannot run cd because cd is a built-in command and xargs can run only executable files.
  2. Even if you run cd in a sub-process called from xargs, it will not have any effect on the parent process as explained above.

The solution is to run a sub-shell, inside it run cd and then you can execute commands in the new current directory.

ls | xargs -L 1 bash -c 'cd "$0" && pwd && ls'