Feeling like an idiot right now. Why does this not work?
echo "/some/directory/path" | xargs -n1 cd
Feeling like an idiot right now. Why does this not work?
echo "/some/directory/path" | xargs -n1 cd
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.
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:
xargs cannot run cd because cd is a built-in command and xargs can run only executable files.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'
I reached here with the same question.
My workaround to the sub-process limitation was to use command substitution.
For example it could look something like:
cd "$(echo '/some/directory/path')"