Skip to content

Instantly share code, notes, and snippets.

@craftslab
Last active December 10, 2020 04:29
Show Gist options
  • Save craftslab/e0e388d08190028abaef633c6e47da1e to your computer and use it in GitHub Desktop.
Save craftslab/e0e388d08190028abaef633c6e47da1e to your computer and use it in GitHub Desktop.
process explorer
#!/usr/bin/env bash
plist="\
proc1,\
proc2"
send_kill=false
version="v1.0.0"
kill_process()
{
kill "-9 $1"
echo ""
echo "PID $1 KILLED"
echo ""
}
report_process()
{
cmd=$(ps -eo pid,user,cmd,pcpu,pmem --sort pcpu | grep "$1" | grep -v "grep")
echo "${cmd}" | while read -r line; do
if [ -z "${line}" ]; then
continue
fi
pid=$(echo "$line" | awk '{print $1}')
user=$(echo "$line" | awk '{print $2}')
cmd=$(echo "$line" | awk '{print $3}')
pcpu=$(echo "$line" | awk '{print $(NF-1)}')
pmem=$(echo "$line" | awk '{print $(NF)}')
echo ""
echo " PID: $pid"
echo "USER: $user"
echo " CMD: $cmd"
echo " CPU: $pcpu"
echo " MEM: $pmem"
echo ""
if [ "$send_kill" = true ]; then
kill_process "$pid"
fi
done
}
show_version()
{
echo "$version"
exit 0
}
show_help()
{
echo "Process Explorer"
echo ""
echo "Usage: procexp [OPTIONS] NAME"
echo ""
echo "Options:"
echo " -k Kill process."
echo " -v Show version."
exit 0
}
while getopts ":hkv" opt; do
case "${opt}" in
h)
show_help
;;
k)
send_kill=true
;;
v)
show_version
;;
*)
show_help
;;
esac
done
shift $((OPTIND -1))
pname=$1
if [ -n "${pname}" ]; then
plist=${pname}
fi
IFS=',' read -r -a pbuf <<< "$plist"
for item in "${pbuf[@]}"; do
report_process "$item"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment