all_techie
all_techie

Reputation: 2959

printf command within Bash throwing error

I am using the following command in bash to subtract 2 numbers and print the result. Using bc tool as well

printf '\n"runtime": %s' "$(($a - $b) | bc -l)"

But getting an error

1517359690.775414500: command not found

How should i rewrite my printf command?

Upvotes: 0

Views: 2013

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295618

If your shell is bash, then this could be:

printf '\n"runtime": %s' "$(bc -l <<<"($a - $b)")"

If instead your shell is sh, then this could be:

printf '\n"runtime": %s' "$(echo "($a - $b)" | bc -l)"

Note that we're invoking a separate command -- echo -- whose output is piped into bc, rather than trying to run the numbers as a command themselves.


However, you shouldn't be using printf to create JSON documents in the first place.

Instead, use jq:

start=5.5; stop=6.10
other_value='this is an example string
it crosses multiple lines, and has "literal quotes" within it'
jq -nc \
   --argjson start "$start" \
   --argjson stop "$stop" \
   --arg other_value "$other_value" \
  '{"runtime": ($stop - $start), "other key": $other_value}'

You'll note that the string here is correctly escaped to be included in JSON: " is changed to \", the literal newline is changed to \n, and so forth.

Upvotes: 3

Related Questions