I want to enter every directory retuned by ls
command and execute script.
I tried this (and many other things), but it just does not work
ls | awk '{print $1" && pwd"}' | xargs cd
How to do it without for loop?
I want to enter every directory retuned by ls
command and execute script.
I tried this (and many other things), but it just does not work
ls | awk '{print $1" && pwd"}' | xargs cd
How to do it without for loop?
If you can, use find
as suggested in other answers, xargs
is almost always to be avoided.
But if you still want to use xargs
, a possible alternative is the following:
printf '%s0' */ | xargs -0 -L1 bash -c 'cd -- "$1" && pwd' _
Some notes:
*/
expands to the list of directories in the current folder, thanks to the trailing slash
printf
with 0
(null byte) separates the elements one for each line
the option -L1
to xargs
makes it to execute once for every input line and the option -0
makes it separate the input on the null byte: filenames can contain any character, the command doesn't break!
bash
removes the double quotes and pass it to the inline script as a single parameter, but cd
should put double quotes again to interpret it as a single string; using --
makes the cd
command robust against filenames that start with a hyphen
to avoid the strange use of $0
as a parameter, is usual to put a first dummy argument _