[TIP] Force variable substitution within single quotes in BASH

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

  1. David
    Posted 24.January.2011 at 16:02 | Permalink

    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?

  2. ptankov
    Posted 25.January.2011 at 11:09 | Permalink

    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
    done
    

    the 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 after echo, 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.

  3. Jim
    Posted 20.June.2011 at 21:53 | Permalink

    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’


Post a Comment

Required fields are marked *
*
*

Follow

Get every new post delivered to your Inbox.