Linux and Command-Line Basics
$ X=1
$ bash -c 'echo "[$X]"'
$ export X
$ bash -c 'echo "[$X]"'When the commands above are run in order, which of the following is the pair of outputs of the two bash -c commands?
- A[] and [1]
- B[1] and [1]
- C[] and []
Show answer and explanation
Answer: A. [] and [1]
A variable that is only assigned, as in "X=1", is a shell variable: it can be used only inside that shell and is not passed to child processes it starts (here a new bash). With export it becomes an environment variable, and its value is inherited by child processes started afterwards. Therefore the first output is [] and the second [1]. Because of the single quotes, $X is expanded not in the parent shell but inside the child bash.
- A. Correct. Until it is exported, X is not passed to child processes.
- B. A shell variable that is only assigned is not inherited by child processes.
- C. Child processes started after export inherit the value of X.