0

I'm new on bash and I'm trying to write a bash script that will save user's multilines inputs (a text with newlines, somes lines of code, etc.). I need to allow newline (when you press "Enter"), multiline paste (when you paste few lines "Ctrl+V") and set a new key, instead of "Enter", to validate, send the input and continue to the next step of the script.

I tried with read but you can not do multiline.

echo "Enter content :" 
read content

I found an example with readarray here (How to delete a character in bash read -d multiline input?) that allow to press "Enter" for newline but each words separate by space are separate in the array. I would like to have only the lines separated.

echo "Enter package names, one per line: hit Ctrl-D on a blank line to stop"
readarray -t pkgs

Do you have any ideas ? Or there is maybe a completely different way to do it ? Thank you for your help.

1 Answer 1

1

You can set IFS to newline so that only newlines will separate items in the array.

IFS=$'\n' readarray lines

The first line read will be ${lines[0]}, the second ${lines[1]}, etc. ${#lines[@]} tells you how many lines, and the last one will be ${lines[${#lines[@]}-1]}.

To loop over the array, you should use "${lines[@]}", not ${lines[*]}; the latter will take you right back to looping over individual words.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello and thank you for this answer. I didn't know about IFS. For other people that are interested : echo "Enter package names, one per line: hit Ctrl-D on a blank line to stop" IFS=$'\n' readarray lines for line in ${lines[*]} do echo "$line" >> result.txt done
Don't try to put blocks of code in comments; it doesn't work well. :) Also see my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.