Why are commands executed inside backticks not affecting the current shell?

I know that backreferences are used for command substitution, but why don't these commands affect the current shell. For example, executing the following command changes my current working directory to the previous directory I was in.

$> cd -

      

On the other hand, the following command shows me the contents of my previous working directory, but does not change it.

$> ls `cd -`

      

There can be other examples in a similar way, for example

$>ls `PATH=""`

      

Here it shows the contents of my working directory, but the variable PATH

is unchanged.

Is the command / expression inside reverse steps executed in a sub-shell?

+3


source to share


2 answers


It works like eval(exp)

in some programming languages:

it is evaluated in the outer scope, which is a "child" of the current scope (also called a subshell ) - this way it "knows" all the vars in the current env and only returns the result - hence it cannot cause any side effect on the current environment.



Backticks are old style and $()

should be used instead. To learn more about command substitution - see the docs

+2


source


The squats are different $BASHPID

- they're fork

from the original shell.

$ echo $BASHPID; echo "`echo $BASHPID`"; echo $BASHPID

      



When you fork on Unix, the copy-on-write child process inherits (or simply inherits when trying to copy) the data from the parent process. A child process (subshell) can read all variables, but writing to any of them will create a private copy for the child (or it already has a copy of its own if the kernel does not write to write).

+1


source







All Articles