shell脚本根据端口占用情况执行命令

shell脚本根据端口占用情况执行命令

徐徐
运维
发布于2024-12-03 17:19:01
🌺前言
检查3000端口是否占用,进而执行不同的命令

bash
#!/bin/bash

# 检查是否安装了netstat
if command -v netstat >/dev/null 2>&1; then
    PORT_STATUS=$(netstat -tuln | grep ':3000 ' | wc -l)
elif command -v ss >/dev/null 2>&1; then
    PORT_STATUS=$(ss -tuln | grep ':3000 ' | wc -l)
else
    echo "Neither netstat nor ss is available. Please install one of them."
    exit 1
fi

# 判断端口3000是否被占用
if [ "$PORT_STATUS" -gt 0 ]; then
    # 端口被占用时执行的命令
    echo "Port 3000 is in use. Executing command A..."
    # 在这里替换为实际要执行的命令A
    your_command_a
else
    # 端口未被占用时执行的命令
    echo "Port 3000 is free. Executing command B..."
    # 在这里替换为实际要执行的命令B
    your_command_b
fi
文章最后更新于 2024-12-03 17:19:01
留言
暂无数据

~~空空如也