Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

how to create input read with newline in bash?

Writer Sophia Terry

I want to ask

I have a problem, how do I get input in bash to do newlines?

read -p "List Name: " list
cat <<EOF >names.txt
List Names:
$list
EOF

i can not do a new line or use the command \n , how to add a new line command ?

I want result output names.txt like this

List Name : Robert James Samuel
1

2 Answers

If you want a list with one item per line, you can use readarray:

# Read list
echo "Enter one name per line, finish with Ctrl-D:"
readarray -t list
# Use list as normal array
echo "Name List:"
printf '%s\n' "${list[@]}"

Now you can use list as normal array, e.g. ${list[1]}.

By default bash uses a space character as a delimiter to separate words. This shell script uses a space character as a delimiter to separate three names that are input by the user. Paste the following shell script into a text file named input-names.sh, right click input-names.sh, select Properties -> Permissions tab and put a checkmark to the left of Allow executing file as a program.

#!/bin/bash
# Read multiple inputs
echo "Type three names separated by space characters."
read name1 name2 name3
echo "List name :"
echo " $name1"
echo " $name2"
echo " $name3"

The following output will appear after executing the above script.

:~$ ./input-names.sh
Type three names separated by space characters.
Robert James Samuel
List name : Robert James Samuel 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy