[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: builtin "read -d" behaves differently after "set -e#

From: Greg Wooledge
Subject: Re: builtin "read -d" behaves differently after "set -e#
Date: Wed, 6 Feb 2013 08:46:34 -0500
User-agent: Mutt/

On Wed, Feb 06, 2013 at 12:39:45AM +0100, Tiwo W. wrote:
>         When using this in a script of mine, I noticed that this fails
>         when errexit is set ("set -e").

Most things do.  set -e is crap.  You should consider not using it.

>         * why does it work with "set +e" ?

Because set +e disables the crap.

>         * what is the recommended way to disable splitting with "read"?

What splitting?  You only gave a single variable.  There is no field
splitting when you only give one variable.

>         set -e
>         read -d '' var2 <<EOF
>            but
>            this
>            fails
>         EOF
>         echo "$var2"

Are you actually asking how to force read to slurp in an entire file
including newlines, all at once?  Is that what you meant by "splitting"?

Well, you already found your answer -- stop using set -e.  By the way,
you may also want to set IFS to an empty string to disable the trimming
of leading and trailing whitespace, and use the -r option to suppress
special handling of backslashes.  Thus:

  IFS= read -rd '' var2 <<EOF

In case you're curious why set -e makes it fail:

  imadev:~$ IFS= read -rd '' foo <<EOF
  > blah
  > EOF
  imadev:~$ echo $?

read returns 1 because it reached the end of file for standard input.
>From the manual: "The return code is zero, unless end-of-file is
encountered, read times out (in which case the return code is greater than
128), or an invalid file descriptor is supplied as the argument to -u."

So, if you're reading all the way to EOF (on purpose) then you should
ignore the exit status.  set -e doesn't permit you to ignore the exit
status on commands where the exit status indicates a nonfatal condition
(such as read -d '' or let i=0).  This is why set -e is crap.

Also see http://mywiki.wooledge.org/BashFAQ/105

reply via email to

[Prev in Thread] Current Thread [Next in Thread]