-1

My goal is to do

filename=user2.json
userJson=${cat ${filename} | jq}

This obviously don't work.


According to this answer, this should work (but it doesn't):

  filename=user2.json
  eval "userJson=\${cat $filename | jq}"

Error: ${cat user2.json | jq}: bad substitution


cat user2.json | jq works fine on its own


Here are other combinations I tried that didn't work:

1.

  filename=user2.json
  eval "userJson=\${cat $(filename) | jq}"

Error: ${cat | jq}: bad substitution

2.

  filename=user2.json
  eval "userJson=\${cat '${filename}' | jq}"

Error: ${cat 'user2.json' | jq}: bad substitution

1 Answers1

2

Wrong brackets:

filename=user2.json
userJson=$(jq <"$filename")
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • Surely jq takes filename args ? (I just deleted my UUOC comment.) – Paul_Pedant Aug 28 '22 at 10:48
  • 1
    @Paul_Pedant Rather jq . -- "$filename" (jq -- . "$filename" doesn't work!) and even then it doesn't work for a file called -, while jq < "$filename" works regardless of what $filename contains and also has the advantage of not running jq if the file can't be opened (and in that case gives an error message that's consistent regardless of which command is being redirected and with many shells also give the line number within the script where the error occurred). – Stéphane Chazelas Aug 28 '22 at 14:24