Feeling like an idiot right now. Why does this not work?
echo "/some/directory/path" | xargs -n1 cd
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityThe 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.
cd `echo "/some/directory/path" | cut -d\ -f1`
(Note that I added 'cut' to split on spaces and grab the first item the way xargs does)
Nov 3, 2010 at 20:27
xargs
can't run cd
since it's, of necessity, a shell builtin and xargs
can only run free-standing executables. What you said is true about subprocesses, however.
Nov 3, 2010 at 20:36
cd `port file libcudd | sed -e 's/\/Portfile//'`
(usually long ones you don't want to handle manually, like this MacPorts Portfile location).
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'
ls | xargs ...
in this example. It should be passing in the value for $0
, like echo "/some/directory/path" | xargs -L 1 bash -c 'cd "$0" && pwd && ls'