This question already has an answer here:

How can I give space " " as input in shell script ?

Ex :

echo " Enter date for grep... Ex: Oct  6 [***Double space is important for single date***] (or) Oct 12 "
read mdate 
echo $mdate

I get the output as Oct 6 but I want Oct 6.

marked as duplicate by Gilles linux Oct 9 '14 at 7:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You already have Oct  6 in $mdate, your problem is that you're expanding it when printing. Always use double quotes around variable substitutions. Additionally, to retain leading and trailing whitespace (those are stripped by read), set IFS to the empty string.

IFS= read -r mdate
echo "$mdate"

The -r (raw) option to read tells it not to treat backslashes specially, which is what you want most of the time (but it's not the problem here).

  • can we also ensure the beginning and ending spaces are not dropped? read toto ; echo "$toto" : when i enter ______this____ (_ are spaces) it outputs this (I believe this is not something done by read, but by the shell's line policy? how to change it? stty raw before the read, or something?) – Olivier Dulac Oct 9 '14 at 7:44
  • 1
    @OlivierDulac Yes, this needed IFS=. This is about the shell, it has nothing to do with terminal settings. – Gilles Oct 9 '14 at 7:49
  • I found it : OLDIFS="$IFS" ; IFS="" read toto ; echo "__${toto}__" ; IFS="${OLDIFS}" – Olivier Dulac Oct 9 '14 at 7:50
  • oh; thanks for that quick reply, that I only saw when I typed my 2nd comment ^^ +1, sir! – Olivier Dulac Oct 9 '14 at 7:51
  • 1
    @OlivierDulac No need for anything so complicated. Just set IFS for the duration of the read call. – Gilles Oct 9 '14 at 7:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.