简体   繁体   中英

Add string values to variable depending on another variable

I have the following variable in bash: $httpd_server_count, this variable can contain values like 1 or 2 and etc. And depending on this value I need to get proper value in $settings variable. The string is:

If the $httpd_server_count=1:

settings={'httpd1': {'server': 'settings.server1'},

If the $httpd_server_count=2:

settings={'httpd1': {'server': 'settings.server1'}, {'httpd2': {'server': 'settings.server2'},

and count can be is up to 10 and more. How to properly organize it in code?

I'm a bit unclear on what you are needing, but it appears you want to read the value of httpd_server_count and based on the number 1, 2, whatever generate the server strings needed. If I have it right, one way would be to use a simple C-Style for loop based on httpd_server_count . For example:

#!/bin/bash

str=
for ((i = 1; i <= $httpd_server_count; i++)); do
    str="${str}{'httpd$i': {'server': 'settings.server$i'}, "
done

echo -e "str\n\n$str"

You would still be responsible for trimming the trailing , and appending a closing '}' if required. But, if your value of httpd_server_count is 1 , then you get:

{'httpd1': {'server': 'settings.server1'},

If it is 2 , you get:

{'httpd1': {'server': 'settings.server1'}, {'httpd2': {'server': 'settings.server2'},

This may give you an idea you can run with. Let me know if you have any questions. (by the way, a json parser is generally preferred, like jq )

Use functions in bash to make the code more portable and efficient. Just put the code in a wrapper like below. Logic is similar to this David C. Rankin's answer ,

function settingsGenerator() {   
    local httpd_server_count=$1

    local i
    local settings

    for ((i=1; i<=httpd_server_count; i++))
    do
        settings="${settings}{'httpd$i': {'server': 'settings.server$i'}, "
    done

    printf "%s" "$settings"
}

and store the output of the function in a variable, settings as

settings=$(settingsGenerator 2)
printf "%s\n" "$settings"
{'httpd1': {'server': 'settings.server1'},{'httpd2': {'server': 'settings.server2'},

Using arrays would require a small change something like,

function settingsGenerator() {   
    local httpd_server_count=$1

    local i
    local settings=()

    for ((i=1; i<=httpd_server_count; i++))
    do
        settings+="{httpd$i': {'server': 'settings.server$i'}, "
    done

    printf "%s" "${settings[@]}"
}

Use for loop:

#!/bin/bash
for i in `seq $httpd_server_count`; do
    settings+="{'httpd$i': {'server': 'settings.server$i'}, "
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM