0

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.

2 Answers2

0

With a small change, the third solution works:

# Set Auth Header
AUTH_HEADER="authorization: Bearer $TOKEN"

Get Version

VERSION=$(curl -s ${IS_PUBLIC:+ -H "$AUTH_HEADER"} "https://api.github.com/repos/$REPOSITORY/releases/latest" | jq -r '.tag_name')

Found the decisive clue here: Bash: optionally passing arguments to a command.

0

The second one should work if you use correct quoting while building the array. You want one array element per command argument, and don't embed quotes in the values. Basically, when building the array, you quote the same way you would directly on the comand line.

args=(
  -s
  "https://api.github.com/repos/$REPOSITORY/releases/latest"
)

Set Auth Header

if [ $IS_PUBLIC == 0 ]; then args+=(-H "authorization: Bearer $TOKEN") # Corrected quoting here fi

Get Version

VERSION=$(curl "${args[@]}" | jq -r '.tag_name')