bash environment-variables string – How to Get Variable Name from Command Output

bashenvironment-variablesstring

I have some string, and want to split on colon ":" assigning on variable with name from left part and value from right part. For example:

echo "Title: Some title" | sed 's/:.*//'

gives me wanted variable name "Title", and:

echo "Title: Some title" | sed 's/.*: //'

gives me the value "Some title".

My problem is how to assign variable named "Title" by the output of above command.

I can assign the value like $(echo "Title: Some title" | sed 's/.*: //) but can't find how to assign the name

Best Answer

Depending on how this is going to be used and your bash version, you would probably be better off using an associative array.

Failing that, I suggest you fake one.

For the sake of completeness, you can actually do this using eval. Note that eval is dangerous and you shouldn't use this unless you have to.

eval "${string/: /=\"}\""