Read input in shell script

I want to write a script that read the input to variable.
I want the input screen to have 2 lines, where the values already input will appear above the input line
for example if I want to input the words below:

like
love
live
life

The screen will display like this:

  1. Before any input
Input words:
  1. after entering
like

:

like 
Input words:
  1. after entering
life

:

like love live life
Input words:

I have tried the following but it keeps giving multiple lines, any ideas?

#!/usr/bin/ksh
n=2
p=""
while [[ $n != "x" ]]
do
    echo "Input words: \c"
    read n
    p=$p" "$n
echo $p
done

You'll need man console_codes to position the cursor arbitrarily on the screen, but be aware that not all systems and terminal emulators accept these. Alternatively, try man termcap / terminfo .
You should prefer printf over echo , btw.

Hiya

output=""
input=""
while
    echo "$output"
    read input
do output+=" $input"
    # Well this goes forever until you hit CTRL+C
done

hth

Thanks you for your effort, but I dont want multiple lines on the screen.

OSX 10.7.5, default bash terminal...

#!/bin/bash
n=2
p=""
while [[ $n != "x" ]]
do
    read -p "Input words:- " n
    clear
    p=$p" "$n
    echo "$p "
done

This will print on the top line...

EDIT:
I have just noticed it is calling ksh, apologies chaps...
The bash version works...

I dont want my screen to look like this:

Input words: like
like
Input words: love
like love
Input words: live
like love live
Input words: life
like love live life
Input words:

I want it to look like this after :

ike love live life
Input words:

I thought you said the bash version worked?

Well you been told where to look, and showed how it could work.
Since you love scripts, why dont you try yourself a bit?

I wonder that you state that clear would not work for you...

Assuming TERM is set in your environment to correctly indicate your terminal or terminal emulator type, the following should work:

#!/usr/bin/ksh
addword() {
	tput clear
	if [ "$input" != "" ]
	then	if [ "$output" != "" ]
		then	output="$output $input"
		else	output="$input"
		fi
	fi
	printf '%s\nInput words (ctl-d when done): ' "$output"
	read -r input
}
input=
output=
while addword
do	:
done
echo

Although written and tested using ksh , this should work with any POSIX-conforming shell (e.g., ash , bash , dash , ksh , zsh , etc.).

1 Like