I am creating and setting a variable in my shell script using following expression.

eval "test2"="'Test Name's Test'"

But it results in following error

-sh: eval: line 1: syntax error: Unterminated quoted string

How can I fix this.

link|improve this question

50% accept rate
feedback

3 Answers

up vote 3 down vote accepted

To get an idea of what will actually be run when eval-ing some string, try to echo it first. eval-ing it is like copying the output of echo into the shell and running that:

echo "test2"="'Test Name's Test'"
test2='Test Name's Test'

There are three single quotes there, which will never run. And since you can't include single quotes in Bash single-quoted strings (it doesn't even support backslash escaping, unlike many other languages), you'll have to use double quotes if you want to eval something like that:

echo "test2"="\"Test Name's Test\""
test2="Test Name's Test"

But as @daniel pointed out, the eval is unnecessary. And you shouldn't be using eval in any case - The only case I have ever seen of useful eval is with getopt output.

link|improve this answer
feedback

The error message is quite clear here. Unterminated quote is probably referring to the three single quotes on the right hand side.

link|improve this answer
feedback

First: why the eval? You could just say test="...".

Second: You can't put a single quote ' into a string delimited by single quotes. You can't even escape it with a backslash. So to put a single quote into such a string, you have to end the single-quoted string and insert the single quote (which has to be escaped):

test2='Test Name'"'"'s Test'; echo $test2
test3='Test Name'\''s Test'; echo $test3

The problem with eval is that it adds another expansion round, so you have to escape the internal "'s

eval test2="'Test Name'\"'\"'s Test'"; echo $test2
eval test3="'Test Name'\''s Test'"; echo $test3
link|improve this answer
I am using eval to create a variable assign with a value when someone wants calls my function with a string representing the name of new variable created – Sirish Kumar Jan 7 at 7:50
feedback

Your Answer

 
or
required, but never shown

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