3

I can do the following:

$ FOO="text"
$ echo $FOO
$ text

But how can I wrap it inside bash -c construct? I tried this but failed:

$ FOO="text"
$ bash -c 'echo $FOO'
$ # return nothing

The reason I ask this because I need to execute another 3rd party code that need to be wrapped inside bash -c

2

2 Answers 2

6

Try

$ export FOO="text"
$ bash -c 'echo $FOO'

export command is used to export a variable or function to the environment of all the child processes running in the current shell.

Here's the source

The "bash" command starts a child process where its parent is your current bash session.

To define a variable in parent process and use it in child process, you have to export it.

Sign up to request clarification or add additional context in comments.

1 Comment

FOO=text bash -c 'echo $FOO' would work as well - in this case, the environment variable FOO is set just in the context of the process (bash) being created.
-1

you can use bash -c 'FOO=test; echo \$FOO' or export FOO=test;bash -c 'echo $FOO'

5 Comments

tried that, it won't do, it returns $FOO instead.
export FOO="text" bash -c 'echo $FOO' is the right way, ignore my answer
you can also use bash -c '$FOO=test;echo \$FOO', i always do like this
@ceilKs update your answer so as to help others that may seek the same assistance
Sorry but the left part of condition doesn't met the requirement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.