Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add defer keyword #183

Open
yassinebenaid opened this issue Feb 14, 2025 · 2 comments
Open

Add defer keyword #183

yassinebenaid opened this issue Feb 14, 2025 · 2 comments
Assignees

Comments

@yassinebenaid
Copy link
Owner

yassinebenaid commented Feb 14, 2025

What will be the impact of having a new keyword defer that defers the execution of a given command.

global shell

defer echo defered

echo foobar

Output:

foobar
defered

functions

it works in functions too:

function foo(){
    defer echo defered

    echo foobar
}

foo

Output:

foobar
defered

sub-shells

works on subshells and command substitution as well:

(
    defer echo defered

    echo foobar
)

Output:

foobar
defered

command substitution

echo $(
    defer echo defered

    echo foobar
)

Output:

foobar
defered

This feature is inspired by the Go programming language.

Thoughts: @simonw @ianwalter @pohart @tangowithfoxtrot @vanodevium

@vanodevium
Copy link

@yassinebenaid As for me, defer is mostly golang based word. What about finally?

Anyway, idea is cool.

LGTM

@tangowithfoxtrot
Copy link
Contributor

Agree. I think this is a cool idea. In the case of functions would something like the following work?

my_func() {
  defer rm -rf "$TMP_DIR"
  TMP_DIR="$(mktemp -d)"
  
  # do stuff in $TMP_DIR...
}

# $TMP_DIR was deleted when my_func() is out-of-scope

If so, I could see it being very nice to have. Not sure how challenging it would be to implement it in such a way that if you had something like set -u in your script, it could handle TMP_DIR being set later, but ideally that would work too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants