Thursday, October 6, 2022

[SOLVED] Read command stops the execution of the bash script

Issue

I have a bash script where I use the read command to store a multiline string into a variable, but for some reason that I still don't understand, it's stopping the execution of the script, with exits with status code 1.

#!/usr/bin/env bash

# some setup code
# ...

read -r -d '' test_command <<EOF
CI_TIMEOUT_MINUTES=20 \
FOO=foo \
BAR=${bar} \
yarn test "path/to/tests/"
EOF

echo "test_command: ${test_command}"

if ! kubectl exec -it "$pod" -- /bin/sh -c "${test_command}"; then
# ...

When executing the script, it exits with status 1 at the read command execution, without reaching the line echo "test_command: ${test_command}".


Solution

You have set -e set, and read exits with 1 exit status because there was no zero byte in the input, which causes set -e to terminate the script.


I advise not to store commands as strings. Store commands as functions, then serialize to string. I would do:

test_command() {
   # Quotes!
   CI_TIMEOUT_MINUTES=20 \
   FOO=foo \
   BAR="${bar}" \
   yarn test "path/to/tests/"
}

# First pass test_command function as a string, then call that function.
... sh -c "$(declare -f test_command); test_command"
# or to nicely handle arguments.
... sh -c "$(declare -f test_command);"' "$@"' _ test_command "arg1" "arg2"
# Anyway, here sh seems like an overkill.
... env CI_TIMEOUT_MINUTES=20 FOO=foo BAR="${bar}" yarn test "path/to/tests/"


Answered By - KamilCuk
Answer Checked By - Cary Denson (WPSolving Admin)