-#!/bin/bash
+#!/usr/bin/env bash
+
+yes_or_no() {
+ local answer
-function yes_or_no {
while true; do
- read -rp "$* [y/n]: " yn
- case $yn in
- [Yy]*) return 0 ;;
- [Nn]*) echo "Aborted" ; return 1 ;;
+ read -r -p "$1 [y/n]: " answer
+
+ case "$answer" in
+ [Yy]*)
+ return 0
+ ;;
+ [Nn]*)
+ return 1
+ ;;
esac
done
}
-PSOUTPUT="$(pgrep -l exe)"
-
-echo "Grepping ps for wine executables..."
-if [ -n "$PSOUTPUT" ]; then
- echo "The following processes have been found:"
- echo "$PSOUTPUT"
- yes_or_no "Would you like to send sigTERM to all processes?" && pgrep exe | xargs kill
- echo "Verifying that all processes have been cleaned..."
- sleep 7
- PSOUTPUT="$(pgrep -l exe)"
- echo "After sending sigterm to every process, these ones still remain:"
- echo "$PSOUTPUT"
- yes_or_no "Would you like to send sigKILL to all processes?" && pgrep exe | xargs kill -9
- echo "Verifying that all processes have been cleaned..."
- if [ -n "$PSOUTPUT" ]; then
- echo "Still some processes around. Please remove them manually..."
- echo "$PSOUTPUT"
- else
- echo "All processes have been cleaned!"
- fi
-else
- echo "No wine executables found"
+get_wine_processes() {
+ pgrep -af '\.exe([[:space:]]|$)'
+}
+
+echo "Searching for Wine executables..."
+
+processes="$(get_wine_processes)"
+
+if [[ -z "$processes" ]]; then
+ echo "No Wine executables found."
+ exit 0
fi
+echo "The following processes have been found:"
+printf '%s\n' "$processes"
+
+if ! yes_or_no "Would you like to send SIGTERM to all processes?"; then
+ echo "Aborted."
+ exit 0
+fi
+
+pkill -f '\.exe([[:space:]]|$)'
+
+echo "Waiting for processes to terminate..."
+sleep 7
+
+processes="$(get_wine_processes)"
+
+if [[ -z "$processes" ]]; then
+ echo "All processes have been cleaned!"
+ exit 0
+fi
+
+echo "The following processes are still running:"
+printf '%s\n' "$processes"
+
+if ! yes_or_no "Would you like to send SIGKILL to all remaining processes?"; then
+ echo "Some processes remain:"
+ printf '%s\n' "$processes"
+ exit 1
+fi
+
+pkill -9 -f '\.exe([[:space:]]|$)'
+
+sleep 1
+
+processes="$(get_wine_processes)"
+
+if [[ -n "$processes" ]]; then
+ echo "Some processes are still running. Please remove them manually:"
+ printf '%s\n' "$processes"
+ exit 1
+fi
+
+echo "All processes have been cleaned!"
+