Home > OS >  User input line by line by hit enter
User input line by line by hit enter

Time:12-30

I want to make a script , when user inputs endless new lines (with enter) and when he hits dot (.) then enter it will stdout his list to file. just like "mailx -s" command.

for example:

Enter names (hit dot (".") to interrupt) :
name1
name2
name3
name4
and so on

.
EOF

I have try the following:

read -rp 'Please enter the details: ' -d $'\04' data
declare -p data

The exist code is ctrl D, And what i need is dot as an exist code to an file.

Thanks in advance.

CodePudding user response:

Don't try to read it all with a single read. Do a loop and check each line. Something like:

#!/bin/sh

content=
while read line && test "$line" != . ; do
        content="${content}${line}
"
done

printf "%s" "$content"

CodePudding user response:

I'll modify William Pursell's answer slightly, since you might as well read into an array rather than overwriting the same string every time (which is O(n^2)):

#!/bin/bash

# or use echo if you want the prompt on a separate line
printf 'Please enter the details: '

lines=()
while IFS= read -r line && [[ "$line" != . ]]; do
  lines =("${line}")
done

printf '%s\n' "${lines[@]}"

See https://mywiki.wooledge.org/BashFAQ/001 if you haven't already, it covers using IFS= and -r. You might not want IFS= depending on your exact requriements.

  • Related