First things first: A string with spaces is enclosed in either single quotes ‘ or double quotes “. The difference you ask? Single quotes are treated “as is”: No variable replacement, no parsing, just a string. If you want to embed a variable value, you have to concatenate the string. Period. Double quotes allow dynamic values via variables:
NAME="Andreas" echo "The name is $NAME" # Output: The name is Andreas
This would print my name in the echo line.
Okay, so now what if you need a quote in a echo line? Exactly, the same that is used to initiate and terminate the string? Well, you have to escape it. Let me make this clear: We are still working on a default Linux Bash now. Double quotes are relatively easy:
echo "A string with a \" is fine." # Output: A string with a " is fine.
Same goes for variables:
NAME="Name with a \" character." echo "Value: $NAME" # Output: Value: Name with a " character.
Single quotes are a little more tricky:
echo $'String with a \' in it.' # Output: String with a ' in it.
And as a variable:
NAME=$'Name with a \' in it.' echo 'Value: '$NAME # Output: Value: Name with a ' in it.
Okay, so now you can have quotes in strings that are framed by the same quotes. This is the beginning and I’d start practicing this for bash. I will continue this tutorial with PowerShell embedding:
Write-Host "A string containing a `" character." # Output: A string containing a " character.
As you can see, the escaping character is different from bash: PowerShell uses a ` to escape newline (`n) or quotes (`”).
As we all know, MS is known for their consistency. Single quotes are treated differently:
Write-Host 'A string containing a '' character.' # Output: A string containing a ' character.
Isn’t that awesome?
So why am I explaining this?
Try to imagine the following scenario: You are working on a Windows-Machine (with PowerShell) and would like to run a command via SSH (basically a Linux tool) on a remote Linux server that runs BaSH. I’d suggest working from bottom (the command on the Linux server) to top (the command being written in the PowerShell environment). First execute it on Bash, then via SSH and finally embed it in the PowerShell command. This way you always know on which level you are and which escapes you are going to need.
I will continue this tutorials because this always gave me a headache. Especially considering variables parsed on the executing host, the remote machine or coming from a command line. One has to work very concentrated here and always visualize where a certain part of a command is executed.