gpt4 book ai didi

json - 从 Bash 脚本输出 JSON

转载 作者:IT老高 更新时间:2023-10-28 12:47:06 26 4
gpt4 key购买 nike

所以我有一个输出服务器详细信息的 bash 脚本。问题是我需要输出为 JSON。解决此问题的最佳方法是什么?这是 bash 脚本:

# Get hostname
hostname=`hostname -A` 2> /dev/null

# Get distro
distro=`python -c 'import platform ; print platform.linux_distribution()[0] + " " + platform.linux_distribution()[1]'` 2> /dev/null

# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
uptime="$days days, $hours hours, $minutes minutes, $seconds seconds"
else
uptime=""
fi

echo $hostname
echo $distro
echo $uptime

所以我想要的输出是这样的:

{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}

谢谢。

最佳答案

如果只需要输出一个小的JSON,使用printf:

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

或者,如果您需要生成更大的 JSON,请使用 heredoc正如 leandro-mora 所解释的那样.如果您使用 here-doc 解决方案,请务必点赞 his answer :

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

一些较新的发行版有一个名为:/etc/lsb-release 或类似名称 (cat/etc/*release) 的文件。因此,您可以可能摆脱对 Python 的依赖:

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

顺便说一句,您可能应该取消使用反引号。它们有点过时了。

关于json - 从 Bash 脚本输出 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12524437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com