TIL explicit subshell as function bodies in Bash

tl;dr: In bash you can use parenthesis for the function body instead of the usual braces and it will make that function run explicitly in a subshell.

I’ve been writing functions like this:

foo() {
    # function body
}

And then managing the side effects. I had no idea I could just use an explicit subshell! I could write the same thing like this:

foo() (
    # function body
)

No more worrying about side effects of over-writing variables at the global scope, but globals are still readable. No more tracking what directory I started in, or worrying about what directory I end off in.

Tags

#index

#til

#bash

#cli

Navigation

index

tags

prev ⏰

⏰ next

updated: 2024-07-09 16:12:48

generated: 2024-08-16