简体   繁体   中英

why single quotes and double quotes works differently in “bash -c”?

While using bash -c option to spawn new shell before running shell script,
I encountered unexpected action.

When I use single quotes , new shell is spawned to run the script.

$ bash -c 'echo pid is $$'
pid is 53465
$ bash -c 'echo pid is $$'
pid is 53466
$ bash -c 'echo pid is $$'
pid is 53477

But double quotes didn't.

$ bash -c "echo pid is $$"
pid is 2426
$ bash -c "echo pid is $$"
pid is 2426
$ bash -c "echo pid is $$"
pid is 2426

I carefully read similar question and bash manual but could not find why.
Anyone knows the reason why?

So when you execute the command

$ command "echo pid is $$"

The double quotes ensure that the command command gets a string passed where all substitutions are done. So assuming that the pid of the interactive shell is 1234. You will get the equivalent

$ command "echo pid is 1234"

When you use single quotes, the command gets passed the string echo pid is $$ where $$ is just like any string. If the command is now bash , $$ has a special meaning

$ bash -c 'echo pid is $$'

So now you get the PID returned of the executed command bash and not of your interactive shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM