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


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/: /=\"}\""
| improve this answer | |
  • Seems like great idea. I have "GNU bash, version 4.2.8" and script returns [unexpected EOF while looking for matching `"']. I'm looking for possible solutions right now... – zetah Feb 24 '12 at 7:34
  • @zetah change the single quotes to escaped doubles. – Kevin Feb 24 '12 at 7:40

This is a rather strange thing to be doing, but I guess you could construct an export statement:

$ export $(echo "Title: Some title" | sed 's/:.*//')="$(echo "Title: Some title" | sed 's/.*: //')"
$ echo $Title
Some title
| improve this answer | |
  • Thanks. I guess there is no other way then exporting as environment variable? I mean I can't make local variable name from command output? – zetah Feb 24 '12 at 7:21
  • You can craft the assignment using bash string manipulation. If I haven't made a mistake, I believe it would be (assuming the string is in a variable string) "${string/: /='}'" – Kevin Feb 24 '12 at 7:25
  • @zetah you're better off with this, but if you really need a local, see my answer. – Kevin Feb 24 '12 at 7:33
  • Make that ${string/: /=\"}\"" – Kevin Feb 24 '12 at 7:42
  • 1
    @zetah You can use typeset or local instead of export, if your shell has them (bash does). – Gilles 'SO- stop being evil' Feb 24 '12 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.