delavnog delavnog - 22 days ago 6
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 $?
echo $PAYLOAD


This results in:

1
yyy


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

Answer

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
payload=$(<xxx)
echo $?
echo "$payload"

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

Comments