Can I use the $( ... ) syntax with multiline commands?

Viewed 1593

I often use backticks in with long commands that I break up with backslash-newlines for readability. When I replace the backticks with the $( ... ) syntax, I get errors.

For instance, I set a variable using curl and jq inside backquotes (reading from my Trello daily to-do list and returning card.id and card.name for everything but a specific card):

AllCardsInDTL=\
`\
curl -s "https://api.trello.com/1/lists/$DailyTasksListID/cards\
?$WhoMe\
&fields=name,id,pos\
"\
| jq  '\
    .[] | \
    if .name | test ("Tasks here are copied.*") \
    then empty \
    else .id, .name \
    end \
    '\
`  # End of AllCardsInDTL=

That has no problems and the shell variable consists of alternating lines of ID and Name values.

But if I replace the backquoteswith $( ... ), I get an error from jq:

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
\
jq: 1 compile error
(23) Failed writing body

It's not clear to me from the error, whether the ) is not actually terminating the command started by $( or whether inside the $( ... ) the backslash is not being interpreted as I expect.

I would like to be able to use the $( ... ) syntax because there are times when I want to nest one subshell inside another and that's very difficult to do with backquotes.

2 Answers

You can certainly use \ to escape end-of-lines inside a $(...) expression. Also note that you don't need those \'s in the jq expression inside the single quotes.

I would probably write it something like this:

AllCardsInDTL=$(
curl -s "https://api.trello.com/1/lists/$DailyTasksListID/cards\
?$WhoMe\
&fields=name,id,pos" |
jq  '.[] |
    if .name | test ("Tasks here are copied.*")
    then empty
    else .id, .name
    end
    '
)

I can't test this, since I don't have a useful value for $DailyTasksListID nor am I equipped to authenticate to trello at the moment.

Yes. Demo:

echo $(echo foo
echo bar
echo baz
)

Output:

foo bar baz
Related