0

I have simple script

#!/bin/bash
SENTENCE=""
while read word
do
    SENTENCE="$SENTENCE $word"
done

whose interaction with the user may result in the following:

a
a
b
a b
c
a b c
d
a b c d

How can I have the string displayed at the right in the same line as the user in order to have the output

a                                 a
b                                 a b
c                                 a b c
d                                 a b c d
1
  • How can I complete this AINSI sequence: echo -e "\e[1a b c d"
    – user123456
    Oct 13, 2016 at 0:14

1 Answer 1

1

Assuming the simplest case (a short word, no line-wrapping, no concern about reaching the end of the screen with scrolling), you could do this

#!/bin/bash
SENTENCE=""
tput sc
while read word
do
    SENTENCE="$SENTENCE $word"
    tput rc
    tput hpa 20
    printf '%s\n' "$SENTENCE"
    tput sc
done

That uses two terminal features which are in most of the terminal descriptions you would use:

  • save/restore cursor position (the sc and rc parameters), and
  • horizontal position (the hpa parameter).

You could hardcode the corresponding escape sequences, at the expense of readability...

By the way, some may suggest using the up-arrow escape, but that has the same problem with scrolling at the end of the screen, as also would \e[F (CPL, which is not in your terminal description).

For moving horizontally, you could use the right-cursor with a parameter, e.g.,

tput cuf 20

which would be \e[20C.

At the end of the question, there is comment about \e[1a, but ANSI escape sequences are case-dependent, that is not the same as \e[1A (which moves the cursor up by one line). This may be what you had in mind:

#!/bin/bash
SENTENCE=""
while read word
do
    SENTENCE="$SENTENCE $word"
    tput cuu1
    tput hpa 20
    printf '%s\n' "$SENTENCE"
done

which is easier to read than

#!/bin/bash
SENTENCE=""
while read word
do
    SENTENCE="$SENTENCE $word"
    echo -en '\e[A'
    echo -en '\e[20C'
    echo "$SENTENCE"
done
1

You must log in to answer this question.

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