1

Can anyone tell me how can I make the follow command to work properly?

SERVER=192.168.1.1

ping $SERVER (It Works)

ping '$SERVER' (It doesn't work)

I want this to compose a more complex command that needs quotes!

Thank you all!!

jesse_b
  • 37,005
Kellyson
  • 135

2 Answers2

3

Use double quotes.

When you use single quotes, you get exactly what you typed, whilst double quotes interpolate, per the example below:-

$ x=1
$ echo 'This is $x'
This is $x
$ echo "This is $x"
This is 1
Paul T
  • 301
  • This is more or less what I'm looking for @Paul T... but the command need to execute inside single quotes: 'ping $SERVER', the variable need to be expanded inside them... 'ping 192.168.1.1'... – Kellyson Feb 21 '18 at 03:33
  • Why can't the command be in double quotes instead of singles? What's the wider context that forces you to use single quotes? If you can show that, perhaps I can help. BTW I upvoted your question. – Paul T Feb 21 '18 at 04:07
  • @Kellyson variable expansion does not happen inside single-quotes, so you can not use single quotes here. This is not a matter of preference or options, or something that can be worked around somehow - it's how single-quotes work, and it's what they're for. Use double quotes. – cas Feb 21 '18 at 05:17
  • @Paul T, thanks for answer. The command I want to use is:

    #ssh -t $SRV1 'ping $SRV2'

    The remote SSH command execution requires single quotes. If I use #ssh -t $SRV1 'ping 192.168.1.2' it works, but I need use a variable for SRV2.

    Thank you!

    – Kellyson Feb 21 '18 at 20:21
  • @Kellyson no, ssh does not require a single quote. ssh doesn't require any quotes unless you need to control if/how word splitting, file globbing, and/or variable expansion etc happen. Try ssh -t "$SRV1" ping "$SRV2". BTW, if you need the remote host to see the double-quote (e.g. when the ssh command uses a remote variable), use \ to escape the double-quote inside the quoted command. e.g. ssh "$SRV1" "echo \$HOSTNAME: pinging $SRV2; ping $SRV2" – cas Feb 22 '18 at 00:43
0

You can use double-quotes like so:

SERVER=192.168.1

ping "$SERVER.1"
ping "$SERVER".1
ping $SERVER.1

Notice the last example has no quotes.

However, see Expansion of variable inside single quotes in a command in Bash for a much more in-depth reading on the topic.