[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.

Advertisements
This entry was posted in console and tagged . Bookmark the permalink.

4 Responses to [TIP] Force variable substitution within single quotes in BASH

  1. David says:

    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 says:

    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 says:

    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’

  4. mancdaz says:

    Bad example as test is a bash keyword. Do it with more single quotes, like this

    #myvariable=’1 2 3 4′
    #echo ‘my variable contains ‘$myvariable”
    my variable contains 1 2 3 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s