Home > Net >  Loop through all files in a directory and subdirectories using Bash and invoking a php command
Loop through all files in a directory and subdirectories using Bash and invoking a php command

Time:11-05

I'm very new to bash scripts but I was looking to build a script that essentially goes through a directory and its subdirectories and files.

The top level directory would be the location of images so top level may be "293 House Street" and in that would be subdirectories of each room "Bathroom", "Kitchen", etc. and within those sub directories would be images. There may also be images found in the top level.

I want to essentially invoke the PHP command once a file has been found and provide some arguments for the data to be used.

php process_directories.php -a "293 House Street" -p "PATH_OF_FILE" -f "FILE"

-a Would be the Address // This will always be the same for each file found in the current directory.

-p Would be the path of the file

-f Would be the file.

Is there a good way to possibly make a script like this?

CodePudding user response:

Modify your php script such that it takes the full path as single parameter and extracts the 3 sub-parts (easy). Then, with the find utility:

find "293 House Street" -type f -exec php process_directories.php {} \;

Note: naming process_directories.php a php script that processes a single file is a bit counter-intuitive. Are you sure you will remember what it does in, let's say, one week?

CodePudding user response:

I don't think that you can do it directly with the command find but you can loop through its results with Bash:

#!/usr/bin/env bash

while IFS= read -d '' -r filepath
do
    dirpath="${filepath%/*}"
    filename="${filepath##*/}"
    php process_directories.php -a "293 House Street" -p "$dirpath" -f "$filename"
done < <(find . -type f -print0)  
  • ${filepath%/*} is $filepath but with the last / up to the end removed (that is the directory path).
  • ${filepath##*/} is $filepath but with the start up to the last / removed (that is the file name).
  • find . -type f will output all the files in the current directory and its sub-directories, prefixed with ./, which ensures that the two bullets above work correctly.
  • The option -print0 of find combined with read -d '' ensures, by using the NULL byte as separator, that you can process correctly each path (which in Linux filesystems, can be composed of any character but NULL).

Remark: You could also modify your PHP script to do the same things, instead of using the Shell

  • Related