Skip to content

Instantly share code, notes, and snippets.

@suewonjp
Last active March 10, 2018 00:26
Show Gist options
  • Save suewonjp/82183aa403003fa1f1624c3fde3561a0 to your computer and use it in GitHub Desktop.
Save suewonjp/82183aa403003fa1f1624c3fde3561a0 to your computer and use it in GitHub Desktop.
Bash function that lets you interactively kill arbitrary process with pattern matching (See the comment below for an example usage)
killProcess() {
if [ $# -lt 1 ]; then
echo "Usage: ${FUNCNAME[0]} [pattern for process name]"
return
fi
local procs=() selected=
case "$( uname )" in
Darwin*|CYGWIN*) mapfile -t procs < <( pgrep -fil "${1}" ) ;;
*) mapfile -t procs < <( pgrep -fl "${1}" ) ;;
esac
selected=$( selectFromArray procs )
if [ "${selected}" ]; then
local ans tmp pid
read -ra tmp <<< "${selected}"
printf "\e[1;36m${tmp[@]}\e[0m\n"
pid=${tmp[0]}
while :; do
read -rn 1 -p "Kill it? (Y/y/n/?) :" ans
case "$ans" in
Y) echo; kill -9 "${pid}"; return ;;
y) echo; kill "${pid}"; return ;;
n) echo; return ;;
?) printf "\nType \e[4;33m%s\e[0m for normal kill, \e[4;33m%s\e[0m for force kill, \e[4;33m%s\e[0m for abort\n" \
"y" "Y" "n"
;;
esac
done
fi
}
@suewonjp
Copy link
Author

Example

IMPORTANT : This function uses selectFromArray function
Make sure you copy it too when you copy this function

### Just call the function without argument to see simple usage guide
$ killProcess
Usage: killProcess [pattern for process name]

### Provide pattern for the process to kill
### I assume I want to kill a vim process not responding for some reason.
$ killProcess vim
1) QUIT!
2) 69188 vim not.responding.txt
3) 69189 vim working.txt
#? 2
69188 vim not.responding.txt
Kill it? (Y/y/n/?) :?
Type y for normal kill, Y for force kill, n for abort
Kill it? (Y/y/n/?) :y

### When there are multiple processes with the pattern you have provided,
### the function will let you choose the specific process you want to kill.
### Now you type the number for the process and press Enter (In this example, 2)
### And it will ask you whether or how to kill the process.
### Type y for normal kill (This might not kill some busy processes)
### Type Y for force kill (Mostly will kill any process)
### Type n for abort
### Type ? for help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment