因此,我有一个输出服务器详细信息的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"}谢谢。
发布于 2012-09-21 13:00:27
如果只需要输出一个小的JSON,那么可以使用printf
printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"或者,如果需要生成更大的JSON,可以使用leandro-mora解释的heredoc。如果您使用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)顺便说一句,你可能应该取消使用反引号。它们有点过时了。
发布于 2015-10-20 03:53:09
我发现使用cat创建json要容易得多。
cat <<EOF > /your/path/myjson.json
{"id" : "$my_id"}
EOF发布于 2016-05-02 15:16:31
我根本不是一个bash- not,但我写了一个解决方案,这对我来说非常有效。所以,我决定使用社区的to share it。
首先,我创建了一个名为json.sh的bash脚本
arr=();
while read x y; 
do 
    arr=("${arr[@]}" $x $y)
done
vars=(${arr[@]})
len=${#arr[@]}
printf "{"
for (( i=0; i<len; i+=2 ))
do
    printf "\"${vars[i]}\": ${vars[i+1]}"
    if [ $i -lt $((len-2)) ] ; then
        printf ", "
    fi
done
printf "}"
echo现在我可以很容易地执行它:
$ echo key1 1 key2 2 key3 3 | ./json.sh
{"key1":1, "key2":2, "key3":3}https://stackoverflow.com/questions/12524437
复制相似问题