How to use rpcd from remote system

Can you provide a more complete example of the not working script? The above should work, but with unexpected results.

An echo '{ "cmd_result": "$return" }' will literally output { "cmd_result": "$return" } due to the single quote interpolation rules of Bash. You also need to be very careful with proper quoting and escaping when constructing JSON from external input.

Best is to use jshn (JSON Shell Notation) which will take care of constructing proper responses:

#!/bin/sh

# source jshn shell library
. /usr/share/libubox/jshn.sh

# initialize JSON output structure
json_init

# add a boolean field
json_add_boolean foo 0

# add an integer field
json_add_int code 123

# add a string, take care of escaping
json_add_string result "Some complex string\n with newlines\n and even command output: $(date)"

# add an array with three integers
json_add_array alist
json_add_int "" 1
json_add_int "" 2
json_add_int "" 3
json_close_array

# add an object (dictionary)
json_add_object adict
json_add_string foo bar
json_add_string bar baz
json_close_object

# build JSON object and print to stdout
json_dump

# will output something like this:
# { "foo": false, "code": 123, "result": "Some complex string\\n with newlines\\n and even command output: Fri Jul 13 07:11:39 CEST 2018", "alist": [ 1, 2, 3 ], "adict": { "foo": "bar", "bar": "baz" } }
1 Like