Shell脚本中的字典

尼莎

我正在centos8中开发服务管理器,我有以下代码来获取服务:

i=0
while [ $i -lt $service_count ]; 
do
    service_name=`cat $service_conf_file | get_json_value "['service_groups'][$i]['service']" | sed 's/"//g'`
    status_reader $service_name
    if [ $service_disabled -eq 1 ]; then 
        current_status=disabled
    fi
    
    echo "{'${service_name}' : '${current_status}'}"
    
    
    i=$(( i + 1 ))
   
done
 

但是此代码返回:

{'apache_server' : 'running'}
{'apache_server_2' : 'running'}

我想要像下面的字典中的字典,稍后可以使用Python通过服务名称进行访问。

{"apache_server" : "running" , "apache_server_2" : "running"}

怎么做 ?

罗伯托·曼弗雷达(Roberto Manfreda)

我尝试使用以下脚本:

#!/usr/bin/env sh

printf "{"

i=0
j=100
target=10

while [ $i -lt $target ]; do

    printf "\"$i\" : \"$j\""

    if [ $i -lt $(( $target - 1 )) ]; then
            printf ", "
    fi

    i=$(( i + 1 ))
    j=$(( j + 1 ))
done

printf "}\n"

产生这种输出:
{"0" : "100", "1" : "101", "2" : "102", "3" : "103", "4" : "104", "5" : "105", "6" : "106", "7" : "107", "8" : "108", "9" : "109"}


因此,在您的情况下,应该可以进行以下操作:

#!/usr/bin/env sh

printf "{"

i=0

while [ $i -lt $service_count ]; do
    service_name=`cat $service_conf_file | get_json_value "['service_groups'][$i]['service']" | sed 's/"//g'`

    status_reader $service_name

    if [ $service_disabled -eq 1 ]; then
        current_status=disabled
    fi

    printf "\"$service_name\" : \"$current_status\""
    
    if [ $i -lt $(( $service_count - 1 )) ]; then
            printf ", "
    fi

    i=$(( i + 1 ))
done

printf "}\n"

如注释中所建议,这里使用的技巧printf不会自动将换行符“ \ n”放在字符串的末尾。
您也可以使用,echo但可以指定-e选项。
无论如何,并不是每个系统都支持该选项,因此只需使用即可printf,以确保。


另一个注意事项:
查看所需的输出,看来您想要一个JSON负载,如果您能够在简单的sh上使用BASH,则可以考虑将内容放入数组中,然后通过jq之类的工具将其转换以防止和管理句法错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章