I have a string variable in a bash script file as follows:
string="
test1
test2
"
and I want to check whether a file test.txt
containts this specific string (including the linebreaks. i.e. it should fail if it only contains the following:
this is a test:
test1
test2
and another one
because the linebreaks above test1 and below test2 aren't present.
(The reason I want to check this is because I want to check whether a certain piece of code is in a source file, and if not, add it.)
The following doesn't work:
string="
test1
test2
"
if ! grep -q string "test.txt"; then
echo "$string" >> test.txt
fi
This correctly adds the string to the file, but it does it even if the string has already been added. Also, it performs correctly when I change the string to have no linebreaks.
EDIT:
The answers by @terdon and @steeldriver below work for the string example I wrote above, but they for some reason break for this more realistic example:
string="
if [ -f ~/.script ]; then
. ~/.script
fi
"