Sometimes in a BASH script you need to have single quotes but the value inside them is actually a variable. Here is how to have both the single quotes and the actual value of the variable expanded.
% foo=bar
% echo $foo bar
% echo "$foo" bar
% echo '$foo' $foo
% echo "'$foo'" 'bar'
It seems that double quotes around single quotes make the single quotes expand variables.
Advertisement
3 Comments
It looks like what you actually have is a string containing single quotes as the first and last element. Is that what you meant to demonstrate?
I am trying to demonstrate how you can emit the value of a BASH variable surrounded by single quotes. Consider the following (rather useless) example:
You want to create a file containing a sequence of lines like this:
Now it is '1295946329' seconds since 1970-01-01 00:00:00 UTC
Now it is '1295946330' seconds since 1970-01-01 00:00:00 UTC
Now it is '1295946331' seconds since 1970-01-01 00:00:00 UTC
If you do it like this:
for ((i=0; i<3; i++)); do sec=$(date +%s) echo Now it is '$sec' seconds since 1970-01-01 00:00:00 UTC >> myfile.txt sleep 1 donethe result will be:
Now it is $sec seconds since 1970-01-01 00:00:00 UTC
Now it is $sec seconds since 1970-01-01 00:00:00 UTC
Now it is $sec seconds since 1970-01-01 00:00:00 UTC
To get what you want you must surround
'$sec'with double quotes like this:echo Now it is "'$sec'" seconds since 1970-01-01 00:00:00 UTC >> myfile.txt
or the quotes don’t need to be immediately around
'$sec'. You can surround the whole thing afterecho, like this:echo "Now it is '$sec' seconds since 1970-01-01 00:00:00 UTC" >> myfile.txt
In both cases it does the trick.
when you put single quote in double quote, single quote loss its meaning. It is not what you think how it works
try to expand foo variable out
test=’my test is $foo’