Vinicius Peres
Vinicius Peres

Reputation: 101

Is it possible to output multiple values to different files from a single jq invocation?

I have a curl where I would like to extract two text to two different files, file1.crt and file2.key. currently configured this way by repeating curl.

curl -X GET -H "X-Vault-Token:{{ vault_token }}" https://fopp.com/v1/ACME/data/SSL/fopp.com | jq -r .data.data.crt > /files/nginx/ssl/file1.crt && 
curl -X GET -H "X-Vault-Token:{{ vault_token }}" https://fopp.com/v1/ACME/data/SSL/fopp.com | jq -r .data.data.key > /files/nginx/ssl/file2.key

I would like to know if with jq could handle to extract in just one command.

Upvotes: 0

Views: 419

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295288

Not with only jq itself, but it's easy enough to combine with a bit of shell. If your values can't contain literal newlines, this can be as easy as:

curl -X GET -H "X-Vault-Token:{{ vault_token }}" https://fopp.com/v1/ACME/data/SSL/fopp.com \
| jq -r '.data.data.crt, .data.data.key' \
| { IFS= read -r crt && printf '%s\n' "$crt" > /files/nginx/ssl/file1.crt;
    IFS= read -r key && printf '%s\n' "$key" > /files/nginx/ssl/file2.key; }

If the values can contain newlines, then you need to use a different separator. Consider:

curl -X GET -H "X-Vault-Token:{{ vault_token }}" https://fopp.com/v1/ACME/data/SSL/fopp.com \
| jq -j '.data.data.crt, "\u0000", .data.data.key, "\u0000"' \
| { IFS= read -r -d '' crt && printf '%s\n' "$crt" > /files/nginx/ssl/file1.crt;
    IFS= read -r -d '' key && printf '%s\n' "$key" > /files/nginx/ssl/file2.key; }

Upvotes: 2

Related Questions