The contents of the string in $BIN
likely contains DOS-style newlines, with a carriage return character before each newline character. When printing this to the terminal, the carriage return character(s) moves the cursor back to start of the line, which is why your output looks a bit strange.
Another consequence of this is that your JSON document will be invalid as carriage returns (and newlines) will need special encoding. You also can't insert any character into a JSON value as some characters, notably quoting characters, need to be encoded.
I would suggest two things:
Convert your data file to Unix text format using the dos2unix
conversion tool.
Use a command line tool to create your JSON document that knows how to encode data for JSON. The jo
utility is one such tool.
Using jo
:
#!/bin/sh
bin=$(cat next_entry)
outdir=/tmp/cpupower/$bin
json=$( jo hostname=localhost outdir="$outdir" port=20400 size=100000 )
printf '%s\n' "$json"
Given a file next_entry
with the contents
line 1
line 2
the script above would output
{"hostname":"localhost","outdir":"/tmp/cpupower/line 1\nline 2","port":20400,"size":100000}
If jo
is given its -p
option for pretty-printing the constructed JSON document:
{
"hostname": "localhost",
"outdir": "/tmp/cpupower/line 1\nline 2",
"port": 20400,
"size": 100000
}
OUTDIR
variable appears to be expanded in the value ofJSON
, and the quotes around"port"
and"size"
are inexplicably absent.) (2) It seems obvious to me that theBIN
variable is getting a carriage return in it (from thenext_entry
file); and yet the problem apparently went away without that issue being addressed.