diff --git a/slab/bin/slab-close-window b/slab/bin/slab-close-window new file mode 100755 index 000000000..06cbc698a --- /dev/null +++ b/slab/bin/slab-close-window @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# slab-close-window — close the terminal window that owns the calling tty. +# +# Works in both Terminal.app and iTerm2. Identifies the window by matching +# the controlling tty (`tty -s` from this script's stdin), so running it +# from a background pane / split correctly closes that pane's window +# rather than whatever happens to be frontmost. +# +# Usage: +# slab-close-window # close window owning $(tty) +# slab-close-window /dev/ttys004 # close window owning the given tty +# +# Exit codes: +# 0 closed (or already gone) +# 1 not running from a tty AND no explicit tty argument +# 2 couldn't identify the host terminal (no TERM_PROGRAM hint) + +set -euo pipefail + +TTY="${1:-}" +if [[ -z "${TTY}" ]]; then + if TTY="$(tty 2>/dev/null)" && [[ "${TTY}" != "not a tty" ]]; then + : + else + echo "slab-close-window: not a tty — pass a tty path explicitly" >&2 + exit 1 + fi +fi + +# Strip /dev/ prefix to a tail like "ttys004" so AppleScript's +# `tty ends with` works against either form. +TAIL="${TTY##/dev/}" + +# Pick the host terminal. TERM_PROGRAM is set by the shell of the +# terminal that owns this process, so it's the right cue even when +# another app is frontmost. Fall back to "both" if it's unset. +HOST="${TERM_PROGRAM:-}" +case "${HOST}" in + Apple_Terminal) APP="terminal" ;; + iTerm.app) APP="iterm" ;; + *) APP="both" ;; +esac + +close_terminal_app() { + /usr/bin/osascript <