From 3162ee16e27ce2457d3a45a4e96669be54212bee Mon Sep 17 00:00:00 2001 From: meliurwen Date: Mon, 9 May 2022 14:59:36 +0200 Subject: [PATCH] Improved ssh session detection in zsh's `powermeli` theme checking if an ancestor process is named `sshd` --- zsh/.config/zsh/plugins/powermeli.zsh-theme | 31 +++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/zsh/.config/zsh/plugins/powermeli.zsh-theme b/zsh/.config/zsh/plugins/powermeli.zsh-theme index 6ee2777..5f857af 100755 --- a/zsh/.config/zsh/plugins/powermeli.zsh-theme +++ b/zsh/.config/zsh/plugins/powermeli.zsh-theme @@ -28,13 +28,40 @@ prompt_segment() { unset separator } +# Return the first ancestor PID of the PID of this process with the name issued +# From: https://unix.stackexchange.com/a/459007 +# TODO: Consider reading from `/proc//*` using only POSIX shell builtins +# Note: the `/proc` is not guaranteed to be on all unices (see BSD, Mac...) +# See: +# - https://stackoverflow.com/a/50457487 +# - https://stackoverflow.com/a/1525673 +get_apid() { + ps -Ao pid= -o ppid= -o comm= | + awk -v p="$$" -v ancestor="$1" ' + { + pid = $1; ppid[pid] = $2 + sub(/([[:space:]]*[[:digit:]]+){2}[[:space:]]*/, "") + name[pid] = $0 + } + END { + while (p) { + if ( name[p] == ancestor ) { + print p, name[p] + exit + } + p = ppid[p] + } + }' +} + prompt_context() { if [ $(id -u) -eq 0 ]; then prompt_segment "$SEGMENT_SEPARATOR" black yellow else prompt_segment "$SEGMENT_SEPARATOR" black default fi - if [ -z ${SSH_CLIENT+x} ]; then + # Check if inside an ssh session, also if using `sudo su` + if [ -z ${SSH_CLIENT+x} ] && [ -z ${SSH_TTY+x} ] && [ -z "$(get_apid sshd)" ]; then PROMPT_LINE="$PROMPT_LINE %n " else PROMPT_LINE="$PROMPT_LINE %n%{%F{blue}%}@%{%F{cyan}%}%m " @@ -122,7 +149,7 @@ build_prompt() { unset OLD_BG OLD_SEP printf "%s%s " "%{%f%b%k%}" "$PROMPT_LINE" unset PROMPT_LINE - unset -f prompt_segment prompt_status prompt_virtualenv prompt_context prompt_git + unset -f prompt_segment prompt_status prompt_virtualenv prompt_context prompt_git get_apid } setopt prompt_subst