Reputation: 389
I am developing service manager in centos8 and I have this code to get services:
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
But this code returns:
{'apache_server' : 'running'}
{'apache_server_2' : 'running'}
I want it in dictionary like below, which I can access later by service name using Python.
{"apache_server" : "running" , "apache_server_2" : "running"}
How to do it ?
Upvotes: 2
Views: 1331
Reputation: 2623
I tried using the following script:
#!/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"
which produces this kind of output:
{"0" : "100", "1" : "101", "2" : "102", "3" : "103", "4" : "104", "5" : "105", "6" : "106", "7" : "107", "8" : "108", "9" : "109"}
So in your case something like this should be ok:
#!/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"
As suggested in the comment the trick here's using printf
that doesn't automatically place the newline "\n" at the end of the string.
You could use echo
too but specifying the -e
option.
Anyway not every systems supports that option so simply use printf
, just to be sure.
As another note:
Looking at the desired output it seems you want a json payload, if you are able to use BASH over simple sh you can think about putting stuff into an array then converting it through some tool like jq in order to prevent and manage syntactic errors.
Upvotes: 1