6

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.

0

1 Answer 1

11

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

6
  • 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?) Commented Oct 9, 2014 at 7:44
  • 1
    @OlivierDulac Yes, this needed IFS=. This is about the shell, it has nothing to do with terminal settings. Commented Oct 9, 2014 at 7:49
  • I found it : OLDIFS="$IFS" ; IFS="" read toto ; echo "__${toto}__" ; IFS="${OLDIFS}" Commented Oct 9, 2014 at 7:50
  • oh; thanks for that quick reply, that I only saw when I typed my 2nd comment ^^ +1, sir! Commented Oct 9, 2014 at 7:51
  • 1
    @OlivierDulac No need for anything so complicated. Just set IFS for the duration of the read call. Commented Oct 9, 2014 at 7:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.