Skip to content

Instantly share code, notes, and snippets.

@dstein64
Last active March 18, 2022 01:44
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dstein64/c4e879577fea90ecf8e4282ed4cc1879 to your computer and use it in GitHub Desktop.
# fails to properly return true when running sudo -s
function is_ssh_from_env() {
if [ -n "${SSH_TTY}" ] || \
[ -n "${SSH_CONNECTION}" ] || \
[ -n "${SSH_CLIENT}" ]; then
echo "true"
else
echo "false"
fi
}
# fails to properly return true using xterm
function is_ssh_from_who() {
# method doesn't work in an xterm so just return false
if [ -n "${XTERM_SHELL}" ]; then
echo "false"
return
fi
if [[ $(who -m) =~ \([-:a-zA-Z0-9\.]+\)$ ]]; then
echo "true"
else
echo "false"
fi
}
# fails to return true when not running from linux or when connected to a
# screen not started under ssh
function is_ssh_from_ppid() {
# only works with /proc directory. otherwise return false
p=${1:-$PPID}
if [ -f /proc/$p/stat ]; then
read pid name x ppid y < <( cat /proc/$p/stat )
[[ "$name" =~ sshd ]] && { echo "true"; return; }
[ "$ppid" -le 1 ] && { echo "false"; return; }
is_ssh_from_ppid $ppid
else
echo "false"
fi
}
# not totally reliable but works in a lot of cases (may not work in xterms)
# also the functions it relies on don't return any known false positives,
# only false negatives
function is_ssh() {
if "$(is_ssh_from_env)" || \
"$(is_ssh_from_who)" || \
"$(is_ssh_from_ppid)"; then
echo "true"
else
echo "false"
fi
}
function is_xterm() {
if [ -n "${XTERM_SHELL}" ] || \
[ -n "${XTERM_LOCALE}" ] || \
[ -n "${XTERM_VERSION}" ]; then
echo "true"
else
echo "false"
fi
}
# root prompt red (even in ssh session since if you sudo -s in an ssh session
# there seemingly isn't a way to know you're in an ssh session)
if [ "root" == "$(whoami)" ]; then
USER_COLOR="31m"
else
USER_COLOR="32m"
fi
# if you're running in an xterm, you can't reliably determine remote status,
# so just use default color
if "$(is_xterm)"; then
HOST_COLOR="0m"
elif "$(is_ssh)"; then
HOST_COLOR="36m"
else
HOST_COLOR="34m"
fi
PS1="\n\[\e[${USER_COLOR}\]\u\[\e[0m\]@\[\e[${HOST_COLOR}\]\h "
PS1+="\[\e[33m\]\w\[\e[0m\]\n\$ "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment