Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 17717  / 2 Years ago, fri, april 22, 2022, 1:38:00

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?


More From » bash

 Answers
0

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:




  1. */ expands to the list of directories in the current folder, thanks to the trailing slash


  2. printf with 0 (null byte) separates the elements one for each line


  3. 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!


  4. 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


  5. to avoid the strange use of $0 as a parameter, is usual to put a first dummy argument _



[#42189] Friday, April 22, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tubequ

Total Points: 11
Total Questions: 113
Total Answers: 115

Location: Equatorial Guinea
Member since Thu, Oct 7, 2021
3 Years ago
;