Ubuntu – How to remove element from gsettings array in script

bashcommand linedconfgsettingsscripts

Array in dbus/gsettings has a format [element1, element2, element3, ...].

Gsettings' interface allows only replacing existing array with another, so for instance, adding another item element can be achieved as follows:

gsettings get ${schema} ${key} | grep -q \"${value}\" >/dev/null
if [ $? -ne 0 ]; then
   gsettings set ${schema} ${key} \"`gsettings get ${schema} ${key} | sed s/.$//`, ${value}]\"

Can anyone help me with a script, that checks whether at least one element exists that matches the regex, and if it does, it parses the gsettingsarray string, and removes all matching elements (and puts it back withgsettings set`, but that is trivial).

I tried to find such tool, but I failed to find one. I cannot believe, that nobody yet had a need for such tool…

The question complements How to add element to the gsettings array at the specific location (given by index)?

Best Answer

Using bash for this task should be possible but I prefer doing complex array manipulations with a Python3 script:

#!/usr/bin/env python3

import argparse
import subprocess
import sys

parser = argparse.ArgumentParser()
parser.add_argument("schema", help="gsettings shema", metavar="SCHEMA")
parser.add_argument("key", help="gsettings key", metavar="KEY")
                    help="gsettings value(s) to remove from the KEY array",
                    metavar="VALUE", nargs='*')
args = parser.parse_args()

array = eval(subprocess.check_output(["gsettings", "get", args.schema, args.key]))
for v in args.values:
        value = eval(v)
        value = v
    except ValueError:
        print("Warning: {} not in {} {}".format(value, args.schema, args.key), file=sys.stderr)
subprocess.call(["gsettings", "set", args.schema, args.key, str(array)])

This script allow multiple values to be removed at the same time from the schema/key passed to the script.