7

I'd like to allow a string to be captured with spaces, so that:

echo -n "Enter description: "
read input
echo $input

Would produce:

> Enter description: My wonderful description!
> My wonderful description!

Possible?

2
  • What does it produce on your system? You should probably quote "$input", but it's not clear what error you're seeing. Commented Jun 21, 2014 at 1:30
  • Oh yes, thanks, I wasn't receiving an error, but the string was split at the first whitespace. "$input", this was helpful! Commented Jun 21, 2014 at 3:03

1 Answer 1

20

The main thing to worry about is that when you refer to a variable without enclosing it in double-quotes, the shell does word splitting (splits it into multiple words wherever there's a space or other whitespace character), as well as wildcard expansion. Solution: use double-quotes whenever you refer to a variable (e.g. echo "$input").

Second, read will trim leading and trailing whitespace (i.e. spaces at the beginning and/or end of the input). If you care about this, use IFS= read (this essentially wipes out its definition of whitespace, so nothing gets trimmed). You might also want to use read's -r ("raw") option, so it doesn't try to interpret backslash at the end of a line as a continuation character.

Finally, I'd recommend using read's -p option to supply the prompt (instead of echo -n).

With all of these changes, here's what your script looks like:

IFS= read -r -p "Enter description: " input
echo "$input"
Sign up to request clarification or add additional context in comments.

1 Comment

Sometimes it is much better to point someone to FAQ instead of reinventing the wheel. mywiki.wooledge.org/BashPitfalls#read_.24foo and mywiki.wooledge.org/BashPitfalls#echo_.24foo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.