7

Consider I've set variable site and needs to be printed by echo or printf, but If I use single quote to write something and want to use variable then how?

Example:

$ site=unix.stackexchange.com
$ echo "visit:$site"
visit:unix.stackexchange.com

But If I use single quote:

$ echo 'visit:$site'
visit:$site

Then we know that '' is strong quote and will not expand the variable

I've tried something:

$ echo 'visit:"$site"'
visit:"$site"

but do not succeed. So, I am looking for way to print value inside variable while using single quote.

  • 4
    Why do you need it? – choroba Jun 16 '15 at 10:15
  • 1
    echo 'visite:"'$site'"'? (or echo "visite:\"$site\"" but it's not single quoted…) – fredtantini Jun 16 '15 at 10:16
  • @fredtantini nope, this also seems to ending single quote first – Pandya Jun 16 '15 at 10:38
  • @choroba has posted an answer very similar to my comment. Quoting variable should be prefered (i.e. 'visit:"'"$site"'"') – fredtantini Jun 16 '15 at 10:38
  • 2
    Why do you want to use a hammer as a screwdriver? – kos Jun 16 '15 at 11:12
14

You can't expand variables in single quotes. You can end single quotes and start double quotes, though:

echo 'visit:"'"$site"'"'

Or, you can backslash double quotes inside of double quotes:

echo "visit:\"$site\""
7

When you deal with printing variable content, you should stick with printf instead of echo:

printf 'visit:%s\n' "$site"

will output visit: followed by content of $site and a newline regardless of characters in $site.

1

choroba is correct.

Though if this were some sort of riddle, I'd respond with this:

cat << EOF | sh
> echo 'visit:$site'
> EOF

As jander points out this is wide open for an injection attack. It wasn't a serious answer, so if anyone was considering using something like this, don't use it with untrusted input. For example, validate the $site string as being a valid URL before blindly executing the content. Something like this could help (but the expression provided isn't perfect because it still allows injection, but use that sort of mechanic to test it).

  • I think EOF (itself) working as (another) single quote (something like: bash -c 'echo 'visit:$site'')! – Pandya Jun 16 '15 at 12:31
  • 4
    I hope $site doesn't contain '\nrm -rf /\necho '! – Jander Jun 16 '15 at 17:50
1

If I understand your request right, you can eval(uate) the echoed string. E.g.:

# eval echo 'visit:$site'
visit:unix.stackexchange.com
  • 1
    It appears that what's asked for is the output 'visit:unix.stackexchange.com', with single quotes. – Kusalananda Jan 23 '18 at 11:46

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.