1

Update: I just realized I'm terribly wrong, I don't know how to correct though.

For example, bash -c " echo "$S" " and bash -c ' echo "$S" ' will get totally different output. but my current knowledge is still not enough to conclude correctly.



the title maybe sound a little confusing,

I mean, For example, as default bash -c ' echo " smth " '

if echo requires a single quotes ' for itself usage, echo ' #!$smth '

then bash -c will have to switch to Double quote " instead, to differ echo's single qutoe

so bash -c " echo ' #!$smth ' "

And there is no difference for bash -c whatever single or double quotes.

Do I understand right or please don't hesitate correct me.

Thanks.

3
  • 1
    It depends. If we run bash -c ..., there's two sets of shell command line processing, once in the outer shell before the bash -c ... runs, and once inside it. The way we use different quotes in each determines the way expansions are made, or not made in each. Often you'd use single quotes on the outside, e.g. like find . -type f -exec bash -c 'whatever "$1"' sh {} \;, because with the single quotes, the outside shell doesn't touch the $1, but the inner shell gets to expand it with what it was given (from find here). But bash -c "echo ' smth ' " would be exactly the same either way
    – ilkkachu
    Aug 25, 2021 at 21:05
  • Please specify what you mayn by "I just realized I'm terribly wrong". If you thought better of your question, you can always delete it as long as it has no answers yet.
    – AdminBee
    Aug 26, 2021 at 13:26
  • @AdminBee Thanks for your concern. I mean, the question, the understanding of the usage of the quotes of bash -c is wrong, I thought it didn't matter with single or double quotes for bash -c itself , but actually it matters, it matters a lot. For example, bash -c " echo "$S" " and bash -c ' echo "$S" ' will get totally different output. but my current knowledge is still not enough to conclude correctly.
    – tmp
    Aug 27, 2021 at 4:09

1 Answer 1

2

Double quoted or unquoted variables, like $S or "$S" are expanded in the current shell. When you single quote a string, it is passed literally (minus the singe quotes) to the child process. In your examples you have

...
---> parent-shell
------> child-shell (bash -c)
------> echo command executed in child shell.

In your first example $S is expanded in the parent shell. In your second example $S is expanded to null in the child shell where it is undefined. Exporting the S variable allows it to be passed to the child shell. Example:

[me] S=foo
[me] bash -c " echo "$S" "
foo
[me] bash -c ' echo "$S" '

[me] export S
[me] bash -c ' echo "$S" '
foo
[me] 

Not the answer you're looking for? Browse other questions tagged .