I need to append the following code to the end to all the php files in a directory and its sub directory:
BashFAQ/056 does a decent job of explaining why what you tried doesn't work. Have a look.
Since you're using bash (according to your error), the for
command is your friend.
for filename in *.php; do
echo "text" >> "$filename"
done
If you'd like to pull "text" from a file, you could instead do this:
for filename in *.php; do
cat /path/to/sourcefile >> "$filename"
done
Now ... you might have files in subdirectories. If so, you could use the find
command to find and process them:
find . -name "*.php" -type f -exec sh -c "cat /path/to/sourcefile >> {}" \;
The find
command identifies what files using conditions like -name
and -type
, then the -exec
command runs basically the same thing I showed you in the previous "for" loop. The final \;
indicates to find
that this is the end of arguments to the -exec
option.
You can man find
for lots more details about this.
The find
command is portable and is generally recommended for this kind of activity especially if you want your solution to be portable to other systems. But since you're currently using bash
, you may also be able to handle subdirectories using bash's globstar
option:
shopt -s globstar
for filename in **/*.php; do
cat /path/to/sourcefile >> "$filename"
done
You can man bash
and search for "globstar" for more details about this. This option requires bash version 4 or higher.
NOTE: You may have other problems with what you're doing. PHP scripts don't need to end with a ?>
, so you might be adding HTML that the script will try to interpret as PHP code.