bash:directories:execute_a_command_in_every_directory
BASH - Directories - Execute a command in every directory
for d in [0-9][0-9][0-9] do ( cd "$d" && your-command-here ) done
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;
find ~/Music/ -type d \( ! -name . \) -exec bash -c "cd \"{}\" && fdupes -dN . " \;
If you're using GNU find, you can try -execdir parameter, e.g.:
find . -type d -execdir realpath "{}" ';'
or
find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;
Note: You can use ${0#./} instead of $0 to fix ./ in the front.
or more practical example:
find . -name .git -type d -execdir git pull -v ';'
If you want to include the current directory, it's even simpler by using -exec:
find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;
or using xargs:
find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'
Or
find . -type d -print0 | while IFS= read -r -d '' file; do # ... done
The above examples support directories with spaces in their name.
Or by assigning into bash array:
dirs=($(find . -type d)) for dir in "${dirs[@]}"; do cd "$dir" echo $PWD done
Change . to your specific folder name.
If you don't need to run recursively, you can use: dirs=(*) instead. The above example doesn't support directories with spaces in the name.
The only proper way to put the output of find in an array without using an explicit loop will be available in Bash 4.4 with:
mapfile -t -d '' dirs < <(find . -type d -print0)
Or not a recommended way (which involves parsing of ls):
ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'
bash/directories/execute_a_command_in_every_directory.txt · Last modified: 2021/01/26 14:26 by peter