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?

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
  • 74,655
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