2
[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?

  • See: [Difference between single and double quotes in bash](http://stackoverflow.com/a/6697781/3776858) – Cyrus Mar 26 '15 at 18:04
  • 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 Answers2

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.

John1024
  • 73,527
  • 11
  • 167
  • 163
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

keypulse
  • 21
  • 1