Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: preserve string with spaces input on command line? [duplicate]

Tags:

string

bash

input

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?

like image 922
asking Avatar asked Jun 21 '14 01:06

asking


People also ask

How do you read a string with spaces in shell script?

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).

Does bash ignore whitespace?

Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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"
like image 170
Gordon Davisson Avatar answered Nov 15 '22 05:11

Gordon Davisson