3

Here is a simple script with parameter (set -e):

#!/bin/bash

set -e

echo "begin"
read -r -d '' var <<- EOF
    echo "hello"
EOF
echo "${var}"

I expected no errors here, but the output is just:

begin

And "echo $?" returns 1. Why is this happening? What is wrong with read command here. If I comment out "set -e", everything works fine.

1 Answers1

3

Since you've specified -d '' (no delimiter), there is no complete input line so read is always hitting EOF and returning non-zero.

choroba
  • 231,213
  • 25
  • 204
  • 289
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • `-d ''` means NUL delimiter, isn't it? – codeforester Feb 28 '17 at 06:33
  • I got this example of heredoc from this answer http://stackoverflow.com/a/1655389/7561303. It works fine without (set -e), but I want to stop execution in case of error too. How do I do that? – paratrooper Feb 28 '17 at 06:50
  • 1
    Using `set -e` to trap errors is not very reliable. See [BashFAQ105](http://mywiki.wooledge.org/BashFAQ/105) – codeforester Feb 28 '17 at 06:53
  • I don't understand why you are using `read` at all here. If you want to use read with no delimiter, then you can just as easily make the assignment without it. Just do `var='some multi-line string'` – William Pursell Feb 28 '17 at 07:21
  • Just change your command like `read -r -d '' FOO < – Grisha Levit Feb 28 '17 at 08:14
  • @Grisha That is a great idea! Note that, because of the way `-e` works, you can do any of `read ... && false`, or `read... || false`, or `read ... && true`. Any use of a conditional will prevent the option from causing the script to exit. – William Pursell Feb 28 '17 at 17:26
  • Thanks to all of you, guys. I am going to use '|| true' at the end of the read command. – paratrooper Feb 28 '17 at 17:42