Edit: This question has been edited for context. 1.sh and 2.sh scripts in the original question are replaced by their real-world implementations: monitor.sh and api-check.sh respectively.
Function:
function checkAlive() {
script="$1"
args="${@:2}"
startCheck=$(date +%s)
echo "$@"
tempResult="$( "$@" )"
T_RC="$?"
if [ "$T_RC" -ne 0 ]; then
if [ "$result" = "" ]; then
result="ERRORS: $tempResult"
else
result="$result ,, $tempResult"
fi
fi
RC="$((RC > T_RC ? RC : T_RC))"
timePassed
}
api-check.sh:
method="$1"
url="https://$2"
jwt="$3"
body="$4"
echo "$body"
if ! response="$(curl -s --request "$method" "$url" -w "%{http_code}" --header \
'Authorization: Bearer '"$jwt" --header 'Content-Type: application/json' --header 'Accept: application/json' --data-raw "$body")"; then
echo "$url curl error getting code: $response"
exit 2
fi
monitor.sh:
api_url="foo"
oauth_token"bar"
body='{"address":"Test address"}'
checkAlive "api-check.sh" '"POST" "'$api_url'" "'$oauth_token'" '"'$body'"''
Execution Flow:
- monitor.sh passes the string json body as an argument to checkAlive function (defined above).
- Within checkAlive, the echo "$@" returns:
api-check.sh "POST" "foo" "bar" '{"address":"Test address"}'
- The api-check.sh script never executes properly due to some escaping issue again
Question: What json body should I pass as an argument to checkAlive to escape correctly OR Which line of code and in which script do I need to modify to evaluate the json body correctly?
eval $script $args. First, you don't double-quote your variable expansions ('{"address":"Test address"}'becomes'{"address":"Test''address"}'), then even if you double-quote them,evalwill jinx it... the correct way is to simply useresult="$( "$@" )"args=("${@:2}"), then use it likeresult=$("$script" "${args[@]}"). Avoideval, it's extremely hard to use correctly, and almost never necessary."${@:2}"instead of simply"$2"?checkAliveinstead of just calling2.shon the given JSON?'"'$body'"''?? Jsut"$body"`