2

This question already has an answer here:

[root@localhost ~]# echo $$
16991
[root@localhost ~]# bash -c "echo $$"
16991
[root@localhost ~]# bash -c "echo $$"
16991
[root@localhost ~]# bash -c 'echo $$'
21062
[root@localhost ~]# bash -c 'echo $$'
21063
[root@localhost ~]# bash -c 'echo $$'
21064
[root@localhost ~]# bash -c "echo $$"
16991

I understand that whenever we use single quotes, a new sub-shell is created, and same is not happening with double quotes. Why is it so?

marked as duplicate by glenn jackman, muru, Ramesh, mdpc, Anthon Mar 26 '15 at 20:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • The important and tricky part is the handling of the $$ here - so these above are not duplicates. – Volker Siegel Mar 26 '15 at 19:57
  • Since nobody else has stated this explicitly, as far as I can see — bash -c … always creates a sub-shell (i.e., a new process) regardless of the type of quotes used. The quoting style affects only what command that sub-shell is asked to execute. – Scott Mar 26 '15 at 20:17
2

Summary: The shell performs parameter substitution on strings in double quotes but not on strings in single quotes. $$ is the shell PID but the number you see depends on which shell evaluates it.

Details: Let us consider each case, one at a time.

[root@localhost ~]# echo $$
16991

16991 is the PID of the current shell: let's call it the main shell.

[root@localhost ~]# bash -c "echo $$"
16991

When main shell sees "echo $$", it will substitute in 16991 for $$. Thus, the string passed to bash -c will be echo 16991. That is why 16991 is printed.

[root@localhost ~]# bash -c 'echo $$'
21062

Because 'echo $$' has single quotes, the main shell does not do parameter substitution. The string echo $$ is passed to bash -c. 21062 is printed because it is the PID of the the bash -c process.

[root@localhost ~]# bash -c 'echo $$'
21063

The next time that you run the bash -c process, it has a new PID, this time 21063.

0

Single quotes are strong quoted, which bash will read as parameters, instead of a string as double quotes are intended for. Invoking bash with the -c option will tell it to use non-string parameters as positional parameters. Since single quotes are not strings, they must be interpreted as positional statements.

http://tldp.org/LDP/abs/html/bash-options.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.