I'd choose this approach:
#!/bin/bash
path='/path'
line1='foo'
line2='bar'
while read f; do
if [ ! "$(grep "$line1" "$f")" ] && [ ! "$(grep "$line2" "$f")" ]; then
echo "$line1" >> "$f"
echo "$line2" >> "$f"
fi
done < <(find "$path" -type f -name 'php.ini')
Some notes:
$path
is declared / initialized internally, but it may well be passed as an argument to the script with very few / little modifications if more convenient;
find "$path" -type f -name 'php.ini'
is executed in an external shell and its output is redirected to the while
loop using a process substitution, because piping its output directly to the while
loop would have left $line1
and $line2
out of the while
loop's scope;
-type f
in find "$path" -type f -name 'php.ini'
might be redundant, but just to be safe;
- The two
echo
commands could have been merged into a single echo
command, but that would have required to add an -e
option to escape the \n
sequence; without knowing the exact strings to be appended (which might contain other escape sequences), not using an -e
option and using two echo
commands is safer;
The script searches, recursively, for any file named php.ini
in the $path
path; for each file, if both the grep
commands into the if
statement don't return 0
(i.e. if neither a line containing / matching the $line1
string nor a line containing / matching the $line2
string is found in the file), $line1
and $line2
are appended at the end of the file.
Sample output on a test hierarchy:
user@debian ~/tmp % tree -a
.
├── 1
│ ├── 2
│ │ ├── 3
│ │ │ ├── file
│ │ │ └── php.ini
│ │ ├── file
│ │ └── php.ini
│ ├── file
│ └── php.ini
└── script.sh
3 directories, 7 files
user@debian ~/tmp % find 1 -type f -exec bash -c 'echo -e "{}:\n"; cat {}; echo' \;
1/php.ini:
foo
bar
another line
1/file:
foo
bar
another line
1/2/3/php.ini:
foo
bar
another line
1/2/3/file:
foo
bar
another line
1/2/php.ini:
just one line
1/2/file:
foo
bar
another line
user@debian ~/tmp % bash script.sh
user@debian ~/tmp % find 1 -type f -exec bash -c 'echo -e "{}:\n"; cat {}; echo' \;
1/php.ini:
foo
bar
another line
1/file:
foo
bar
another line
1/2/3/php.ini:
foo
bar
another line
1/2/3/file:
foo
bar
another line
1/2/php.ini:
just one line
foo
bar
1/2/file:
foo
bar
another line