How to run a script/command on all the directories in a directory tree?

How to run a script/command on all the directories in a directory tree?

The below script is just for the files in a single directory, how to run it on all the directories in a directory tree?

#!/bin/sh

for audio_files in *.mp3
do
  outfile="${audio_files%.*}.aiff"
  sox "$audio_files" "$outfile"
done

Hi Temp-usr,

The below command runs on recursive inside 5 folders and get the desired result.
If the same command has been added in a script it will also do the same.

[root@localhost workout]# ls -lR
.:
total 4
drwxr-xr-x. 3 root root 4096 Oct 15 00:03 1
-rw-r--r--. 1 root root    0 Oct 15 00:03 test1

./1:
total 4
drwxr-xr-x. 3 root root 4096 Oct 15 00:03 2
-rw-r--r--. 1 root root    0 Oct 15 00:02 test2

./1/2:
total 4
drwxr-xr-x. 3 root root 4096 Oct 15 00:03 3
-rw-r--r--. 1 root root    0 Oct 15 00:03 test3

./1/2/3:
total 4
drwxr-xr-x. 3 root root 4096 Oct 15 00:03 4
-rw-r--r--. 1 root root    0 Oct 15 00:03 test4

./1/2/3/4:
total 4
drwxr-xr-x. 2 root root 4096 Oct 15 00:03 5
-rw-r--r--. 1 root root    0 Oct 15 00:03 test5

./1/2/3/4/5:
total 0
[root@localhost workout]# find /root/workout/ -iname "test*"
/root/workout/1/test2
/root/workout/1/2/test3
/root/workout/1/2/3/4/test5
/root/workout/1/2/3/test4
/root/workout/test1

cat > Recursive.sh
#/bin/sh

ls -lR
find /root/workout/ -iname "test*"

Thanks
LND

1 Like

Hello temp-user,

You should place this script in parent(first level directory) and could run from there. Also for double checking the working for script, you could use following to make sure first files are getting picked from all the paths.

#!/bin/sh
find -type d 2>/dev/null > Input_file
awk '{sub(/^\./,X,$0);print}' Input_file > Files
 while read path
do
cd $path
   for audio_files in *.mp3
   do
       echo $audio_files
   done
done < "Files"

Once you are fine with above script you could use following actual script then.

#!/bin/sh
find -type d 2>/dev/null > Input_file
awk '{sub(/^\./,X,$0);print}' Input_file > Files
 while read path
do
cd $path
   for audio_files in *.mp3
   do
      outfile="${audio_files%.*}.aiff"
      sox "$audio_files" "$outfile"
   done
done < "Files"

Where file named Input_file has all the paths. You should place this script too in parent(first level directory) and could run from there.

Thanks,
R. Singh

1 Like