Search code examples
bashterminalescaping

Overwrite last line on terminal


My bash-script looks as following:

echo "Description:"
while [ $finishInput -eq 0 ]; do
  read tmp
  desc="$desc"$'\n'"$tmp"
  if [ -z "$tmp" ]; then
    finishInput="1"
  fi
done
echo -n "Maintainer:"
read maintainer

It reads to the desc var until a empty line is passed. After that, i want to read in other stuff.

When executing my current script it looks like this:

Description:
Line 1
Line 2

Maintainer:

I would like to overwrite the last empty line with the "Maintainer:".

I searched for a solution but only found suggestions which were like

echo -n "Old line"
echo -e "\r new line"

which stays on the line and overwrites it. This is not possible in my case.


Solution

  • In your example you delete the text at the same line. When you want to return to the previous line use \e[1A, and to clear that line, use \e[K:

    echo 'Old line'
    echo -e '\e[1A\e[Knew line'
    

    When you want to go N lines up, use \e[<N>A