mklement0 / ttab

macOS and Linux CLI for opening a new terminal tab/window, optionally with a command to execute and/or display settings
285 stars 15 forks source link

Option to include a function or read an interrupt #63

Closed sanidhya-r closed 1 year ago

sanidhya-r commented 1 year ago

Scenario: I have a script that edits a few files and runs the npm project. If it was all part of one script, i could trap the interrupt (ctrl+c) and perform a custom clean up function that may checkout or delete files.

Problem: Since, on using ttab, a new window or tab is opened, i can't assign the same trap function to the new tab or window since the context is lost. Hence, can't perform clean up on interruption.

Proposal: Maybe if there is a way to attach a function or set of actions when an interrupt happens.

# trap ctrl-c interrupt and call cleanup
trap ctrl_c INT

ctrl_c(){
    tput setaf 3; echo -e "\nTerminating Process...\n"; tput sgr0
    cleanUp()
}

this is how i was trapping the interrupt.

cleanUp(){
    tput setaf 3; echo "Cleaning up before exiting"; tput sgr0
    git -C "./project-dir/" clean -df
    git -C "./project-dir/" checkout .
    tput setaf 2; echo "Undid changes. Exiting..."; tput sgr0
    exit
}

this is the clean up function, that would checkout . to remove changes to tracked files and delete untracked files

mklement0 commented 1 year ago

You'll need to install the trap as part of the shell process you're running; here's a minimal example:

ttab 'trap ctrl_c INT; ctrl_c() { echo "Cleaning up... press Enter to exit"; read; exit 1; }; echo Press Enter to exit:; read; exit 0'

Note: This should work with Bash and Zsh. You can also use the shell executable explicitly, by placing bash -c before the command string, but that will call via your default shell, and when your command exits you'll be in that default shell session (the advantage, however, is that you can check your command's exit code).

sanidhya-r commented 1 year ago

@mklement0 really appreciate the quick response. Thanks for the suggestion, it works as expected.

mklement0 commented 1 year ago

Glad to hear it, @sani-Alpha; my pleasure.