Adding config file entries to specific sections

by Thomas Weller   Last Updated January 14, 2018 00:02 AM

I am trying to write a script that configures mySQL. Let's say I want to configure the port to 3333, so I want the config file to contain the lines


At first, I was simply echoing the new lines:

echo "[mysqld]" >> /etc/mysql/my.cnf
echo "port=3333" >> /etc/mysql/my.cnf
echo "[client]" >> /etc/mysql/my.cnf
echo "port=3333" >> /etc/mysql/my.cnf

But then I realized that the config file will contain all entries several times in case I run it multiple times. Therefore I applied a check using a function:

function appendconfig {
    grep -qF "$1" "$2" || echo "$1" >> "$2"
appendconfig "[client]" $cfg
appendconfig "port=3333" $cfg
appendconfig "[mysqld]" $cfg
appendconfig "port=3333" $cfg

That function will only add the line if it does not exist yet.

Unfortunately, when configuring port=3333 in the [mysqld] section, it detects that port=3333is already present (but in [client]).

What way would I write config files like the one from mySQL in a Linux Bash script?

Basically I'm looking for something like

setconfigvalue <section> <value> <file>

so I could write

setconfigvalue [mysqld] port=3333 /etc/mysql/my.cnf

I have tried the suggestions from this U&L sister site question "Editing INI like files with a script".

The accepted answer just provides solutions which are hard coded for the OP's problem. I would need to adapt them, but that's error prone.

I have tried crudini, which seems to be the right tool from its syntax. But it can't parse mySQL config files due to the includes:

crudini --get /etc/mysql/my.cnf client port
File contains parsing errors: <???>
    [line 22]: !includedir /etc/mysql/conf.d/
    [line 23]: !includedir /etc/mysql/mariadb.conf.d/

Related Questions

Shell Script - How to run script after mysql is ready?

Updated November 14, 2015 07:01 AM

How to keep read value after break

Updated January 02, 2016 10:01 AM

sh script works manually but not via cron

Updated February 23, 2016 04:01 AM

Backup script for mysql

Updated October 01, 2018 08:02 AM