How can I kill a process from Terminal using the visible window name?
Figured out this is possible using lsappinfo
:
#!/bin/bash
if [ -z "$1" ]
then
echo "Please provide a process name"
exit
fi
apps_list=$(lsappinfo)
found_line_numbers=$(echo "$apps_list" | grep -nE '([0-9]+\) "[a-zA-Z ]+")' | grep -i "$1" | awk '{print $1}' FS=":")
if [ -z "$found_line_numbers" ]
then
echo "Process named $1 not found"
else
while IFS= read -r line; do
line_pid=$(echo "$apps_list" | tail -n +$line | head -n 5 | grep pid | awk -F ' ' '{print $3}')
echo "Trying to kill process $line_pid"
kill -9 "$line_pid"
done <<< "$found_line_numbers"
fi
The grep/awk combo is a bit awkward, but I couldn't find a better to extract the PID from lsappinfo
.