Output JSON from Bash script

后端 未结 6 1354
暖寄归人
暖寄归人 2020-12-07 18:00

So I have a bash script which outputs details on servers. The problem is that I need the output to be JSON. What is the best way to go about this?

6条回答
  •  难免孤独
    2020-12-07 18:26

    If you only need to output a small JSON, use printf:

    printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"
    

    Or if you need to produce a larger JSON, use a heredoc as explained by leandro-mora. If you use the here-doc solution, please be sure to upvote his answer:

    cat < /your/path/myjson.json
    {"id" : "$my_id"}
    EOF
    

    Some of the more recent distros, have a file called: /etc/lsb-release or similar name (cat /etc/*release). Therefore, you could possibly do away with dependency your on Python:

    distro=$(awk -F= 'END { print $2 }' /etc/lsb-release)
    

    An aside, you should probably do away with using backticks. They're a bit old fashioned.

提交回复
热议问题