I am recursively searching for the occurrence of php scripts being called from other files using the following script.

find . -exec grep -Hn $1 {} \; | grep -v ^Binary;

Works great! Now, I need the returned results to determine the action to be taken next.

r=$(find . -exec grep -Hn $str {} \; | grep -v ^Binary;)

 if [ -z "$r" ];
          Do this
          Do something else

PROBLEM: By it's self the find script returns the results, each on a new line.


However, when assigning the output to the $r variable, the newline character is not preserved and the results are printed on one line making it difficult to read.

./path/to/file.php ./path/to/file.php ./path/to/third_file.php

How do I preserve the newline character while assigning the output into a variable?

  • 1
    Are you sure that the newlines are not preserved when assigning the text to the variable? Are you saying echo $r or echo "$r"? If you're saying echo $r, then the newlines are getting stripped on output. – G-Man Says 'Reinstate Monica' Oct 9 '14 at 23:31

You don't show what you do with $r, but I bet it's

echo $r

You need to enclose the variable in double quotes to preserve the newlines

echo "$r"

Unquoted, the variable is subject to word splitting, where any sequences of whitespace 1 (including newlines) are replaced by a single space 1

1: by default, depends on the contents of $IFS (default: space, tab, newline)

  • I'm outputing the $r to a 'hits.txt' file. Ah yes, "$r" made the difference. Thanks! – pfmasse60 Oct 9 '14 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.