-1

How do I call a command with on argument being the result of cat'ing a file?


  npx aws-api-gateway-cli-test \
  --username $username \
  --password $password \
  --method $method \
  --body cat user.json | jq      # <--------- how am I supposed to write this?

The above snippet results in a parse error


Another attempt:

npx aws-api-gateway-cli-test \
      --username $username \
      --password $password \
      --method $method \
      --body ${cat user.json | jq}

Error: Bad substitution


The following works for reference:

      npx aws-api-gateway-cli-test \
      --username $username \
      --password $password \
      --method $method \
      --body \{\"test\": \"123\"\}
Kusalananda
  • 333,661

1 Answers1

3
npx aws-api-gateway-cli-test \
      --username "$username" \
      --password "$password" \
      --method "$method" \
      --body "$(cat user.json)"

Though in ksh, zsh or bash, you can also do:

npx aws-api-gateway-cli-test \
      --username "$username" \
      --password "$password" \
      --method "$method" \
      --body "$(<user.json)"

$(cmd...), called command substitution expands to the output of cmd stripped of the trailing newline characters and in the case of bash with all the NUL bytes removed. That's fine here for JSON which shouldn't contain NULs (and anyway an argument to an external command cannot contain NULs) and trailing whitespace including newlines in JSON data is not significant.

That particular syntax for command substitution is from ksh is the early 80s and has been standardized for sh by POSIX in the early 90s so is supported by all POSIX-like shells.

The feature itself originated in the Bourne shell in the late 70s but using the cumbersome `cmd` syntax. (t)csh also uses that syntax then. In the rc/es shell, the syntax is `cmd or `{more complex cmd}. While in fish it's just (...), though newer versions now also support $(cmd) (which can also be used inside double-quotes).

In sh-like shells, $(cmd), like $username is subject to split+glob (split only in zsh) when not quoted and in list context, so should be quoted if you want it to be passed as one argument.

For details on $(<file), see Understanding Bash's Read-a-File Command Substitution