I run a php script from console which has multiple echos while processing and I redirect the script output to file. I want to overwrite the previous echos output after each echo.
command: php script.php > output.json
after the first echo output.json contains {"property" : "firstValue" }
after the second echo output.json contains {"property" : "firstValue" }{"property" : "secondValue" } and is no longer a valid json
I want after the second echo ouput.json to contain {"property" : "secondValue" }
STDOUT doesn't work that way. If you're generating multiple lines within a single script, and you only want the last one, you could maybe pipe the output through tail:
php script.php | tail -1 > output.json
Or you could handle the file writing yourself, within the script. Something like:
...
file_put_contents('/path/to/file.json', $someOutput);
...
file_put_contents('/path/to/file.json', $someNewOutput);
...
file_put_contents('/path/to/file.json', $someEvenNewerOutput);
When you want each new line of output to overwrite the last one, read 1 line at a time:
while IFS= read -r line; do
printf "%s
" "${line}" > output.json
done <(php script.php)