0

I want to print only the last line of the output of a command on the same line continuously without clearing the screen. This would be part of another function. Let's say my script has the following pseudo code:

test_project_local_install(){
  install_project
  setup_venv
  run_tests
}

I would want a command to use in the following way:

test_project_local_install(){
  printf "Install Project: "
  install_project | magic_command
  printf "Setup Venv: "
  setup_venv | magic_command
  printf "Run Tests: "
  run_tests | magic_command
}

So that the test_project_local_install command output is the following:

$ > test_project_local_install
$ Install Project: install_project updated output on one line
$ Setup Venv: setup_venv updated output on one line
$ Run Tests: run_tests updated output on one line

The accepted solution to this question does what I want in terms of outputting only last lines of a command continuously but it also clears the screen which is not what I want. I could not figure out a way to adapt the code. Other suggested answers don't match what I'm looking for either. Thanks !

1 Answer 1

0

The easiest attempt is to use the control character carriage return to move the cursor to the line start, override previous content with spaces, carriage return again and print next line.

Actually quite easy to get something started as the following Bash code shows. (can be used either as a separate script or Shell function (but then you might want to remove the exit line))

#!/usr/bin/env bash

# exit if stdin is connected to terminal (script should filter piped input)
[[ -t 0 ]] && exit 0

: "${COLUMNS:=$(tput cols)}"
clear_str=$'\r'"$(printf "%$((COLUMNS-2))s" ' ')"$'\r'

while IFS= read -r line; do
  printf '%s%s' "$clear_str" "${line:0:$COLUMNS}"
done

For a pipeline like ping 1.1 | statusline.sh it shows some kind of ping status line which updates continuously on a single line.

If you need more than that you probably should start look into libraries like ncurses to make a real TUI.

PS: if you add a [[ -n "$line" ]] || continue as first statement in the while loop you could even prevent empty lines to override the last status.

1
  • Just to let you know, I will try this out as soon as I can. Thank you for your time !
    – blue
    Commented Aug 8, 2023 at 23:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .