1

This is one way to assign the contents of a here document to a variable. However, its execution will return a status of 1 without stating a reason.

#! /bin/bash
# set -e -x

# This implementation returns 1
define(){ IFS='\n'; read -r -d '' ${1}; }
define thedoc <<'EOF'
Here is my here doc.
There was an ASCII banana here too,
but `read` would just it concatenate to mush.
EOF
# The here document will print with the following when `set -e` in not invoked.
echo $thedoc

Everything checks out by inspection and even execution provided that set -e is turned off. This is not exclusive to the Banana above but any here doc built by define() above. From where does that error arise?

2
  • I'm not sure what it means, but when I run your code, all the 'n's are replaced with spaces in the value of thedoc. Commented May 31, 2012 at 21:34
  • That behavior is expected. The banana was perhaps a bad choice. :P Commented May 31, 2012 at 23:04

1 Answer 1

3

When you use a null string as the delimiter for read it essentially never sees the delimiter and encounters end-of-file so it sets the return status to 1. You can use a while read loop to avoid that.

From the Bash Reference 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'.

Also, don't use -e. Use explicit error handling. See BashFAQ/105

Additionally, in order to preserve spaces, tabs and newlines and not "concatenate to mush" you must quote the variable that you echo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.