I have a PHP script that retrieves 200 lines from a file by executing a command in Bash using backtick operators. Here’s what the code looks like:
$endline = `(shell execution that returns a number here)`;
$line = $endline - "200";
$lines = "sed -n '".$line.", ".$endline." p' log.txt";
echo $lines;
$file = `$lines`;
echo $file;
This code returns $lines as sed -n '1800, 2000 p' log.txt, but $file doesn’t return any results. When directly using sed -n '1800, 2000 p' log.txt in a Bash terminal, I get the expected results.
What is done incorrectly here? Do the ' characters have to be escaped?
Edit: The shell script added a space after the number, therefore misreading it.
My guess is that it’s
$eofor that your path (log.txt) is not appropriate.I copied and pasted your code, and it works with the following tweaks:
;toecho $lines)$eofto$endline(though you may not need to if$eofis validlog.txtwas a valid path (this is most likely your error)otherwise, it ran as expected.
The reason it would work in Bash but not in PHP is that their “working directory” is not necessarily the same.