Skip to content

Instantly share code, notes, and snippets.

@tkapias
Last active July 21, 2023 11:40
Show Gist options
  • Save tkapias/d7aa9eb102ec3f3047c68a1cf75df0b3 to your computer and use it in GitHub Desktop.
Save tkapias/d7aa9eb102ec3f3047c68a1cf75df0b3 to your computer and use it in GitHub Desktop.
psg: a wrapper to output ps to a pager, colorized and with a filter option
#!/usr/bin/env bash
# executed by bash(1) for non-login shells.
# ==============================
# FUNCTIONS
# ==============================
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# a wrapper to output ps to a pager, colorized and with a filter option
psg() {
Help() {
cat <<- HEREDOC
Display a colorized list of active processes from ps in Less
with optional command line pattern filtering.
Syntax: psg [-h] ["<pattern>"]
options:
-h Print this Help.
"<pattern>" optional: This pattern will use &/ filter in Less
HEREDOC
}
local OPTIND=0
while getopts ":h" option; do
case $option in
h) Help; return 0 ;;
\?) echo -e "Unknown option: -$OPTARG \n" >&2; Help; return 1;;
: ) echo -e "Missing argument for -$OPTARG \n" >&2; Help; return 1;;
* ) echo -e "Unimplemented option: -$option \n" >&2; Help; return 1;;
esac
done
shift $((OPTIND-1))
if [[ -z $(command -v "bat") ]]; then
echo "Requirements: bat could not be found:"
echo "sudo apt install bat"
return 0
fi
if [[ -z $1 ]]; then
_LESS_PROMPT="Output of ps command"
_LESS_CMDS="--"
else
_LESS_PROMPT="Output of ps command (clear filter with &+Enter)"
_LESS_CMDS=$(echo -n -e "+&rss elapsed|${1}\n/${1}\np")
fi
# Less < 632: sticky --header option
if [[ $(less -V | awk 'NR==1 {printf $2}') -gt 632 ]]; then
_LESS_HEADER="--header 1"
fi
ps f -o user,pid,ppid,s,ni,nlwp,tty,%cpu,rss,etimes,args -p $(ps -o pid= -N --ppid $$ --pid $$) \
| awk 'NR==1 {o=$0; a=match($0,$11);}; \
BEGIN{now=systime()} NR>1 {o=$0; $9=int(10*$9/1024)/10"M"; $10=strftime("%m/%d-%H:%M:%S", now-$10);} \
{ printf "%-8s %7s %7s %1s %4s %4s %6s %5s %8s %-14s %s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, substr(o, a);}' \
| bat --color always --decorations never --wrap never --language bash --paging never \
| LESSHISTFILE=/dev/null less -R -L -Q -X -S --tilde --mouse $_LESS_HEADER -I --prompt "$_LESS_PROMPT" "$_LESS_CMDS"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment