If the script doesn't actually need to be in the directory (very few do...and those that do are almost certainly badly written and need to be fixed), you could use find
's -execdir
option to just run the script inside each directory. For example:
find . -mindepth 2 -maxdepth 2 -type d -execdir /path/to/setphase.sh \;
From the GNU find
man page:
-execdir command ;
-execdir command {} +
Like -exec
, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find
.
This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files.
As with the -exec
action, the +
form of -execdir
will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory.
If you use this option, you must ensure that your $PATH
environment variable does not reference .
; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir
.
The same applies to having entries in $PATH which are empty or which are not absolute directory names. If any invocation returns a non-zero value as exit status, then find
returns a non-zero exit status. If find
encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all.
The result of the action depends on whether the +
or the ;
variant is being used; -execdir command {} +
always returns true, while -execdir command {} ;
returns true only if command returns 0.
ls
into a directory before running it there.) – roaima Aug 4 '16 at 20:46find . -mindepth 2 -maxdepth 2 -type d -execdir /path/to/setphase.sh {} \;
will do the job. – cas Aug 5 '16 at 14:55