常に新しい行にプロンプ​​トを印刷して入力を維持する方法

常に新しい行にプロンプ​​トを印刷して入力を維持する方法

私たちは皆、この迷惑な問題を知っています。

$ printf "abc" > some-file
$ cat some-file
abc$ 

それよりも複雑な場合は、プロンプトを混乱させ、$現在のカーソル位置を捨てて、見苦しく見える傾向があります。いくつかの解決策があります(例:ここ)、しかし別の欠点があります。 SSHを介して低速システムにログインすると、プロンプトが表示される前に入力を開始できます。通常、入力はバッファリングされ、できるだけ早く表示されます。ただし、接続されたソリューションの場合、入力は削除されます。

私がどうする

  • 常に新しい行でプロンプトを開始してください。最後のコマンドの出力が新しい行で終わらない場合そして
  • 前のコマンドの実行中に入力された未使用の入力をコマンドラインバッファに保持しますか?

ベストアンサー1

このソリューションは少し組み合わせますトラブルシューティング小さなPerl彫刻:

次のコードは、.bashrc2つの新しい関数injectclear_newline。後者は、印刷プロンプトが必要なときはいつでも呼び出されます。前者は後者内で呼び出されます(詳細はインラインコマンドを参照)。

# injects the arguments into the terminal, from the second link
function inject() {
  perl -e 'ioctl(STDIN, 0x5412, $_) for split "", join " ", @ARGV' "$@"
}
# prints a newline if the cursor is not in position 1
clear_newline() {
  local curpos # local variable to hold the cursor position
  local input  # local variable to hold entered input
  stty -echo # disable echoing
inject '
' # inject a newline to terminate entered input, '\0' didn't work?
  IFS='\n' read -s input # read entered input
  echo -en '\033[6n'
  # ask the terminal driver to print the current cursor position
  IFS=';' read -d R -a curpos # read cursor position 
  stty echo # enable echoing
  (( curpos[1] > 1 )) && echo -e '\033[7m%\033[0m'
  # if cursor not in first column, print a % with inverted colours and a newline
  stty -echo # disable echoing of input to terminal again
  inject "${input}" # inject stored input
  stty echo # enable echo
}

PROMPT_COMMAND='clear_newline' # run clear_newline for every prompt

2番目のstty -echo/stty echoペアは、挿入された入力を隠すために必要です。 bashはプロンプトが完了するとすぐにそれを印刷します。

おすすめ記事