In your first command, you are quoting the variable.
The string passed as the second command line argument to sed
has double quotes around it, and the variable is within those quotes and will be expanded by the shell.
The second command will not work (as expected), as you point out, because the shell would not expand the value of the variable since it's quoted using single quotes.
The first command is correct, but you will have issues if $MY_VAR
contains slashes. If it does, pick a delimiter for the sed
pattern that does not occur in $MY_VAR
:
sed "\@$MY_VAR@d"
A variable is quoted when it appears in quotes. The variable does not need to be "tightly quoted" to be quoted. That is, within the string "hello $world!"
, the variable $world
is quoted even though it does not appear as "$world"
.
What matters is that the string as a whole is quoted. If double quotes are used, then the shell will expand any variables within it.
In the example above, the string "\@$MY_VAR@d"
is quoted, and the variable $MY_VAR
is within it, so it is quoted as well (since it's within the quoted string).
MY_VAR
shell variable? – Stephen Kitt Oct 20 '17 at 14:33$MY_VAR
contents – RomanPerekhrest Oct 20 '17 at 14:33