From 5460c6283752530f3651ac7ab4299a857d46d2a9 Mon Sep 17 00:00:00 2001 From: memdmp Date: Wed, 15 Jan 2025 11:52:10 +0100 Subject: feat: small shell util --- utils/README.md | 5 +++++ utils/session-type.zsh | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 utils/README.md create mode 100644 utils/session-type.zsh (limited to 'utils') diff --git a/utils/README.md b/utils/README.md new file mode 100644 index 0000000..2af8f02 --- /dev/null +++ b/utils/README.md @@ -0,0 +1,5 @@ +# utils + +Directory of utilities developed by zuwu authors for developing cute shell scripts. + +May move out of repository at some point. diff --git a/utils/session-type.zsh b/utils/session-type.zsh new file mode 100644 index 0000000..074cd54 --- /dev/null +++ b/utils/session-type.zsh @@ -0,0 +1,61 @@ +# +# A function for detecting information about the current session, entirely using shell builtins and env variables. +# +# This file is part of the zuwu project - a general-purpose zsh initialization and utility framework. +# It is not used by zuwu at the moment, but rather is provided to shell script developers as a utility function they can integrate into their own codebases +# +# Authors: +# memdmp +# + +function { + local session_extensions=() + local session_base="local" + + # Detect Interactivity & Login State + local is_interactive=false; + local is_login=false; + if [[ $- == *i* ]]; then + is_interactive=true + fi + if [[ $- == *l* ]]; then + is_login=true + fi + if [[ "$is_interactive" && "$is_login" ]]; then + session_extensions+=( + interactive + login + ) + elif [[ "$is_interactive" ]]; then + session_extensions+=(interactive) + elif [[ "$is_login" ]]; then + session_extensions+=(login) + else + session_extensions+=(headless) + fi + + # Detect if local or remote, and the kind + if [ -n "$SSH_TTY" ]; then + session_base=remote + session_extensions+=( + ssh + ssh_tty + ) + elif [ -n "$SSH_CLIENT" ]; then + session_base=remote + session_extensions+=( + ssh + ) + else + # Expensive ssh session detection - spawns a `ps` process. You may want this if you need reliable session type detection + # case $(ps -o comm= -p "$PPID") in + # sshd|*/sshd) session_base=remote; session_extensions+=(ssh);; + # esac + fi + + # Join together into a final, content-type-alike variable + SESSION_TYPE="$session_base/${(j.+.)session_extensions}" +} + +# Example use: +# [[ "$SESSION_TYPE+" == *(+|/)interactive+* ]] && echo "Is in interactive session" -- cgit v1.2.3