Created
January 14, 2020 03:29
-
-
Save jorgerance/667594051ea4d6dcd0d890ff4c1cd56a to your computer and use it in GitHub Desktop.
[killit.sh] Easily killing all processes related to a specific binary #bash #macos #cli #tool #script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| source $HOME/.env/old_dot_custom/fx_msgFormatting.sh | |
| _scriptname="$(basename $0)" | |
| _forceKill=$1 | |
| _stringtokill="$@" | |
| function pidlist_gen() { | |
| ps -eo pid= -o cputime= -o comm= | grep -v grep | grep -i ${_stringtokill} | |
| } | |
| function killThose() { | |
| echo "" | |
| echo "${_pidList}" | while read _pdetails; do | |
| local _pid="$(echo "$_pdetails" | awk '{print $1}')" | |
| msg_att "Killing $_pid..." | |
| kill $(echo "$_pdetails" | awk '{print $1}') >/dev/null 2>&1 | |
| done | |
| } | |
| function main() { | |
| if ! ps -eo pid= -o cpu= -o etime= -o command= | grep -ve grep -ve $_scriptname | grep -i "${_stringtokill}" >/dev/null 2>&1; then | |
| echo "" | |
| msg_err "No PID matches string "$_stringtokill"" | |
| echo "" | |
| exit 1 | |
| fi | |
| echo "" | |
| msg_att "Processes to be killed:" | |
| printf "${YELLOW} ============================================================${RESET_ALL}\n" | |
| while read pline; do | |
| _proc="${pline[@]}" | |
| _procPid="$(echo "$_proc" | awk '{print $1}')" | |
| _procCpuTime="$(echo "$_proc" | awk '{print $2}')" | |
| _procNameLong="$(echo "$_proc" | awk '{$1=$2=""; print $0}' | sed "s/^[ \t]*//")" | |
| _procNameLongChars=$(echo $_procNameLong | wc -c) | |
| _procNameShortMaxChars=40 | |
| _proc_nameShortAppend='' | |
| if [[ $_procNameLongChars -gt $_procNameShortMaxChars ]]; then | |
| _proc_nameShortAppend='[...]' | |
| fi | |
| _procNameShort="${_proc_nameShortAppend}$(echo "$_proc" | awk '{$1=$2=""; print $0}' | sed 's/^[ \t]*//')" | |
| _spid="$(echo "$_proc" | awk '{print $1}')" | |
| _spidproc="$(ps -eo command= ${_procPid} | rev | cut -d'/' -f1 | rev)" | |
| printf "%10s ${CYAN} ${_procNameShort} ${RESET_ALL}\n" $_procPid | |
| done \ | |
| <<<"$(pidlist_gen)" | |
| printf "\n${YELLOW} ============================================================${RESET_ALL}\n\n" | |
| msg_warn "Proceed?" | |
| printf " [y/N]: " | |
| read _yesno | |
| _yesno=${_yesno} # tolower bash 4.x | |
| printf "\n" | |
| if [[ "$_yesno" =~ ^(yes|y)$ ]]; then | |
| msg_info "Running" | |
| killThose | |
| else | |
| msg_info "Exiting...\n\n" | |
| return 0 | |
| fi | |
| } | |
| _pidList=$(pidlist_gen | grep -v grep | grep -i ${_stringtokill} | grep -v ${_scriptname} | awk '{print $1}') | |
| main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment