delavnog delavnog - 7 months ago 32
Linux Question

bash read returns with exit code 1 even though it runs as expected

I have this construct to initialize a variable with the contents of a file:

echo "yyy" > xxx
read -r -d '' PAYLOAD <<< $(cat xxx)
echo $?

This results in:


Why is read returning 1? This is breaking my script, because I run with
set -e


read is returning 1 because it returns 0 only when end-of-file is not encountered.

As per help read:

Exit Status:
The return code is zero, unless end-of-file is encountered

You don't even need a read here, just use $(<file) to read the file content into a variable:

echo "yyy" > xxx
echo $?
echo "$payload"

It is advisable to not use all uppercase variable names in order to avoid clash with ENV variables.