Read a multiline text from a console - supporting arrow keys

Hi,

I try to read a multiline text from a console and write it to a file using a bash script. I want to end reading from a console if a user types the [Enter] key twice. I tried this loop:

while read LINE; do
if [ ! $LINE ] 2>/dev/null; then
   break
fi
echo -e ${LINE} >> $file
done

However, it doesn't support the arrow keys

Do you have any idea?

Thanks in advance

Hi,

Try this one,

readmultiline.sh

#! /usr/bin/env bash
file=file1
while read LINE; do
if [ -z "$LINE" ]; then
   break
fi
echo -e "${LINE}" >>$file
done

$ bash readmultiline.sh
Unix is god^[[B^[[A^[[C^[[D
Linux^[[A^[[D^[[B^[[C^[[A

$ cat -A file1
Unix is god^[[B^[[A^[[C^[[D$
Linux^[[A^[[D^[[B^[[C^[[A$

Cheers,
Ranga :slight_smile:

1 Like

What do you mean? Do you want to skip through earlier input lines with the arrow keys?

1 Like

try this..

while [[ $a < 2 ]]
do
read line
if [[ "$line" != "" ]]
then
let a=0
echo $line >> file_temp
else
let a++;
fi
done

It will stop if user press two consecutive enters..(Means two consecutive Blank inputs..):slight_smile:

1 Like

Hi,

Thank you for your replies. However, I didn't express myself clearly, I just want to be able to move a cursor using the arrow keys while reading an input from a console, because now after pressing an arrow key I got e.g. ^[[D^[[C^[[A^[[B output instead of moving my cursor

Again, what's your purpose? Do you want to skip back in your input lines or do you just want to move left and right? The latter can be achieved - in bash, may be unavailable in other shells - by switching on the readline library functions using the -e option: read -e line The former is much harder to do, like using numbered variables or an array, and writing to the output file consistently will become a nightmare; you might be better off using an editor.

1 Like

I just want to move left/right and if it's possible also up and down, but honestly I don't have any idea how to achieve the latter. Anyway, thank you for your solution with the -e option

What's your system? What's your shell? In BASH, you can use read -e to read lines using readline mode, which lets you edit with left-right keys, but that still doesn't support multiple lines. If you really need deluxe input maybe you should just fire up a text editor for them. nano for instance can be used in restricted mode to prevent them from changing to different files, etc.

1 Like

I'm using the Bash shell, I work on the SunOS 5.9 OS. I'm just wondering if there is a simple way to create a script which would support an input which contains multiple lines, however, it seems that there isn't

Thanks for your reply