mysqlsedmy.cnf

Appending line to config tag if the tag already exists


I am trying to write a script that ensures the following tag and config exist in /etc/mysql/my.cnf:

[mysqld]
bind-address = 0.0.0.0

I currently have the following commands:

sudo sed -i "/bind-address/d" /etc/mysql/my.cnf
sudo sed -i "/\[mysqld\]/d" /etc/mysql/my.cnf
sudo sed -i "\$a[mysqld]\\nbind-address = 0.0.0.0" /etc/mysql/my.cnf

I'm deleting any line that contains 'bind-address' or '[mysqld]', then appending the mysqld tag along with the address I'd like to bind. However, that wouldn't work properly if there were other configs under mysqld. It would end up going from:

[mysqld]
some_config
some_config
bind-address = 127.0.0.1

to:

some_config
some_config
[mysqld]
bind-address = 0.0.0.0

Is there a cleaner way to do this? Thanks.

EDIT: I decided to just replace the default 'bind-address = 127.0.0.1' under /etc/mysql/mysql.conf.d/mysqld.cnf, which would serve the same purpose.


Solution

  • With sed you can define an address range to change the bind address value between \[mysqld\] and next ^ *\[(or end of file):

    sed -i '/\[mysqld\]/,/^ *\[/{s/\(bind-address *= *\).*/\10.0.0.0/}' file