I am seeing "xargs" behaviour that seems to be quite unexpected, in my experience. I use "ls" to find a matching folder name and sending it to "cd" using "xargs". I get the message that the folder doesn't exist. If I don't use "xargs", however, the "cd" works. Also, if I do use "xargs" but send it to "ls" instead of "cd", it also works.
# Identify desired directory
ls -d *[Aa]nt*
201909+ants/
Print the desired command with "echo"
ls -d [Aa]nt | xargs echo cd
cd 201909+ants/
Execute the desired command and get error
ls -d [Aa]nt | xargs cd
xargs: cd: No such file or directory
Confirm that the desired command without "xargs"
cd 201909+ants # This works no problem
cd .. # Go back up
cd 201909+ants/ # This works no problem
cd .. # Go back up
Confirm that "xargs" with "ls"
ls -d [Aa]nt | xargs ls -d
201909+ants/
I'm convinced that this is an ID1OT problem between the keyboard and chair. Can anyone point out where my error lies?
I am using Cygwin's Bash, but rarely do I see a disparity with Linux. I can't remember the last time I saw such a disparity.
cd
is necessarily a shell built-in (it changes the directory used by following commands in the same shell process).xargs
will only run external commands (and there is no/bin/cd
). There is also no purpose in trying to run-exec cd
, because even if it worked, there is no other command to run in the new directory. – Paul_Pedant Jul 01 '22 at 22:08cd $(ls -d *[Aa]nt*)
, which I find more cognitively burdensome than "xargs". But for this simple usage, not so much. – user2153235 Jul 01 '22 at 22:12type cd
will tell you more specifically it is a builtin and adding-a
will implicitly confirm it is not also external (which it is, mostly uselessly, on systems that unlike cygwin and many Linux are fully POSIX conformant; there are several long-existing Qs about this). However, simplycd *[Aa]nt*
should be easy to type; orcd *[Aa]nt*/
to match only a directory especially if you havefailglob
set, although if the former matches a filecd
will just say so. PS: stdio is not involved in xargs running things at all. – dave_thompson_085 Jul 02 '22 at 03:07ls
(and what to do instead)?. BTW, even if there was a/bin/cd
external command, xargs is a child process of your shell (and /bin/cd would, in turn, be a child of xargs) and a child process can not affect the environment (including current working dir) of its parent. a hypothetical /bin/cd couldn't affect the env of xargs, and xargs couldn't affect your shell's env. (that's actually why there's no point in anyone writing a /bin/cd program - it's inherently useless). – cas Jul 02 '22 at 03:33cd
not a program? – Kamil Maciorowski Jul 02 '22 at 05:15cd
saying that the directory dose not exist. It isxargs
saying thatcd
does not exist. – ctrl-alt-delor Jul 02 '22 at 11:49