Shell 脚本中的字典

Dictionary in Shell Script

我正在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
 

但是这段代码returns:

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

我想要它在如下字典中,稍后我可以使用 Python.

通过服务名称访问它
{"apache_server" : "running" , "apache_server_2" : "running"}

怎么做?

我尝试使用以下脚本:

#!/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,您可以考虑将内容放入数组中,然后通过 [=17 之类的工具将其转换=] 以防止和管理语法错误。