如何快速关闭Linux上的服务脚本
前言
对于开发而言,生产部署调试是家常便饭,尤其学习一个新的技术,常常是多个服务共同调试,那么如何快速关闭服务,尤其未将服务添加进环境变量的时候。
关闭Linux指定服务脚本
创建并编辑 find_and_kill.sh
文件;
$ vi find_and_kill.sh
如下内容复制粘贴进文件中:
#!/bin/bash
# 查找输入服务名的进程id,并结束它
# Check if a string argument is provided
if [ -z "$1" ]; thenecho "Usage: $0 <string>"exit 1
fiinput_string="$1"# Find the process ID(s) containing the input string
pids=$(ps aux | grep "$input_string" | grep -v "grep" | grep -v "$0" | awk '{print $2}')# Check if any processes were found
if [ -z "$pids" ]; thenecho "No process found containing the string '$input_string'."exit 1
fi# Output the process ID(s)
echo "Process ID(s) for string '$input_string':"
echo "$pids"# Optionally, ask the user if they want to kill the process(es)
read -p "Do you want to kill these process(es)? (y/n): " confirm
if [ "$confirm" = "y" ]; thenfor pid in $pids; dokill "$pid" && echo "Killed process $pid" || echo "Failed to kill process $pid"done
fi
文件加入写权限,表明是一个可执行文件:
$ chmod +x find_and_kill.sh
文件执行测试:
$ ./find_and_kill.sh nacos
Process ID(s) for string 'nacos':
3175
Do you want to kill these process(es)? (y/n): y
Killed process 3175