I'm trying to conditionally add a header to a curl command.
This is my initial attempt:
# Set Auth Header
if [ $IS_PUBLIC == 0 ]; then
AUTH_HEADER="-H 'authorization: Bearer $TOKEN'"
fi
Get Version
VERSION=$(curl -s $AUTH_HEADER "https://api.github.com/repos/$REPOSITORY/releases/latest" | jq -r '.tag_name')
echo $VERSION output: null, which means the $AUTH_HEADER was not successfully inserted.
Next I tried two solutions based on answers to this question How to conditionally add flags to shell scripts?.
args=(
-s
"https://api.github.com/repos/$REPOSITORY/releases/latest"
)
Set Auth Header
if [ $IS_PUBLIC == 0 ]; then
args+=("-H 'authorization: Bearer $TOKEN'")
fi
Get Version
VERSION=$(curl "${args[@]}" | jq -r '.tag_name')
echo $VERSION output: empty string. Calling curl "${args[@]}" by itself also outputs an empty string.
# Set Auth Header
AUTH_HEADER="-H 'authorization: Bearer $TOKEN'"
Get Version
VERSION=$(curl -s ${IS_PUBLIC:+"$AUTH_HEADER"} "https://api.github.com/repos/$REPOSITORY/releases/latest" | jq -r '.tag_name')
This results in the same output as the second example.
I was surprised that I could not get it to work since the answers from which I got these solutions have many upvotes.