-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

  • `userJson=$(cat "${filename}" | jq .)` – sseLtaH Aug 28 '22 at 10:42
  • @HatLess Thank you! Finally, it works! ( I don't know why you added the dot after "jq" though, seems unnecessary.) – Sebastian Nielsen Aug 28 '22 at 10:42
  • This seems to be mostly a repeat of the issue in your previous question ([Call command with one argument being the result of cat'ing a file](https://unix.stackexchange.com/q/715141)). The only difference is where the command substitution is being used. – Kusalananda Aug 28 '22 at 12:34

1 Answers1

2

Wrong brackets:

filename=user2.json
userJson=$(jq <"$filename")
roaima
  • 107,089
  • 14
  • 139
  • 261
  • 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