Linux下清除Terminal輸出信息的方法
網上看到一種特別的想法,透過Ansi編碼控制輸出信息,記錄一下以備不時之需。
<?php
function replaceOut($str, $finish = false) {
// chr(27) = Esc
echo chr(27) . "[0G"; // Set cursor to first column
echo $str;
if(!$finish) {
$numNewLines = substr_count($str, "\n");
echo chr(27) . "[" . $numNewLines ."A"; // 遊標向上退回 N 行(N 個換行符)
}
}
while (true) {
replaceOut("First Line\nTime: " . date('Y-m-d H:i:s') . "\nThird Line");
sleep(1);
}
/*
Output: (第二行會像時鐘般跳動)
First Line
2020-04-14 15:52:22
Third Line
*/
?>
另外如果只想在Terminal上顯示,不想被導向檔案的話...
<?php
$is_tty = function_exists('posix_isatty') && posix_isatty(STDOUT);
// true => Terminal, false => Redirect to file.
?>
Ansi Escape commands: http://www.inwap.com/pdp10/ansicode.txt