Update var in ini file using bash

前端 未结 4 1435
我寻月下人不归
我寻月下人不归 2021-01-02 02:55

I am attempting to write a bash script to configure various aspects of a server. The context here is replacing a value of a variable in a conf file (ini format) with another

相关标签:
4条回答
  • 2021-01-02 03:00
    awk '/^[ssh-iptables/ {ok=1}
         ok==1 && $0="enabled = false" {print "  enabled = true"; ok=0 ; next}
         {print $0} ' infile > tmp
         mv tmp infile
    
    0 讨论(0)
  • 2021-01-02 03:18

    If you are open to use external applications, you could be interested into the use of crudini.

    Example:

    [oauth2provider]
    module = SippoServiceOAuth2Provider
    backend[] = none
    wiface = public
    
    ; [calldirection]
    ; module = SippoServiceCallDirection
    ; backend[] = none
    ; wiface = internal
    

    A standard grep will not filter commented exceptions.

    With crudini things for consulting, setting and modify are easier:

    $ crudini --get /myproject/config/main.ini oauth2provider wiface
    public
    $ crudini --get /myproject/config/main.ini calldirection wiface
    Section not found: calldirection
    

    I was on a bash-only app and moved to this approach. Just a suggestion.

    Regards,

    0 讨论(0)
  • 2021-01-02 03:20

    You might consider using m4 instead of sed in this case. This uses variable replacement and I think keeps the file looking readable. Your m4 template might look like this:

    [ssh-iptables]
    enabled=SSH_IPTABLES_ENABLED
    

    Now, you call m4 with the following parameters (which can be called from a bash script):

    m4 -DSSH_IPTABLES_ENABLED=true input.m4 > output.ini
    

    or:

    m4 -DSSH_IPTABLES_ENABLED=false input.m4 > output.ini
    

    This is an overly simple way of using m4, if you read about it you'll find you can do some really nifty things (this is the infrastructure upon which autoconf/automake was initially designed).

    0 讨论(0)
  • 2021-01-02 03:21

    Assuming your format is that there are no square-bracket lines (like [ssh-iptables]) within sections, I would use your solution above (with sed) but restrict the query to within that block like so:

    sed -i '/^\[ssh-iptables\]$/,/^\[/ s/^enabled = false/enabled = true/' /etc/fail2ban/jail.conf
    

    The extra part at the beginning tells the following substitution statement to only run between the line that is [ssh-iptables] and the next one that starts with a [. It uses two regular expressions separated by a comma which indicate the bounds.

    0 讨论(0)
提交回复
热议问题