How can I split the following String into key-value pairs using bash?

SOURCE="'key1=val 1' 'key2=val 2'"

My output goal is:

key1=val 1
key2=val 2
  • I can only input a single String as a variable
  • I cannot pass the variable as array
  • I want to output only the key-value pair plain as is
  • I want to honor the quotes, as I don't know how to separate the key-value pairs else
  • My keys never contain spaces, but values will
  • Will the values contain quotes of any type, such as in 'key1=I'm ok'?
    – Kusalananda
    Apr 11, 2022 at 13:10
  • If so, they must be written escaped in the value fields Apr 11, 2022 at 13:11
  • 1
    So, as 'key1=I\'m ok'? I'm asking because a single-quoted string can not contain single quotes in the shell, which may have an impact on ways to write solutions.
    – Kusalananda
    Apr 11, 2022 at 13:17
  • Yes, that's what I ment. Apart from that, I'm not fixed in the way the multi-key-value string has to be defined. I could also change it. It's just important that I only can define a single string "in any way" to transport my key-value pairs, and want to echo out each key-value pair individually. Apr 11, 2022 at 13:20

1 Answer 1


I understand that you are free to define the SOURCE format, so you can make sure, you always have a whitespace between two definitions. In this case, you can remove the ticks at the start and beginning and replace all occerences of ' ' with a newline:

echo "$SOURCE" | sed "s/^'//;s/'$//;s/' '/"'\

Note that I need to switch from double quoting to single quoting to quote the line break.

If you also want to remove the backlash from an escaped tick, do

echo "'key1=foo bar' 'key2=I\'m okay'" | sed "s/^'//;s/'$//;s/' '/"'\

An example to make this fail would be SOURCE="'key1=foo\' ' 'key2=bar'"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .