What is the technique called when you want your variables to disappear after they are run in a subshell?

$ (lookForMe=wee && find -type d -name "${lookForMe}_*")
$ echo $lookForMe
  • Please fix the command syntax. I'd expect the correct syntax is $ (lookForMe=wee && find -type d -name "${lookForMe}_*") right? – filbranden May 16 '18 at 3:48
  • @Filipe okay I added a $. – leeand00 May 16 '18 at 4:42
  • 1
    There's no name for that. Just refer to it as using subshell. – Sergiy Kolodyazhnyy May 16 '18 at 5:03
  • This technic is called making a syntax error ;-) . In your assignment $lookForMe=wee, the variable lookForMe is empty, the statement becomes =wee, and unless you have a program of this name in your working directory (and your working directory is in the path), you will get a command not found error. – user1934428 May 16 '18 at 5:21
  • 1
    Isolating the execution of a piece of code to avoid interactions is often called sandboxing. – xenoid May 16 '18 at 6:17

Shell variables always belong to the current shell. When you spawn a subshell, it is a different shell, and hence has its own set of variables. In your case, you are running the subshell using (......), so bash arranges that the subshell initially gets a copy of all variables of the parent shell, but that's it already. In particular, changes in the variables are not copied back when the subshell ends, nor are variables created in the subshell handed back to the parent shell.

This is not a technique, but it's the way the bash language is defined, and therefore it doesn't make much sense to ask for a name of this.

The whole idea has some similarity to the concept of local variables in most programming languages, so you might be tempted to name the exploitation of this property "creating local variables", but I would be reluctant to do so, because it ignores the fact that at least on the invocation point of the (...), the variables of the parent shells are used to initialize the variables in the subshell.


This does not have a special name apart from "running things in a subshell". It is implied that changes made to the environment in the subshell are not reflected in the parent shell environment.

You may want to call variables created inside the subshell "local variables in the subshell".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.