Files
dotfiles/free-ports.sh
T
GarandPLG dc44eb6d62 Add free-ports script, Docker aliases, and Bun env
Add free-ports.sh script and a corresponding alias in .bash_aliases.
Introduce docker-clean and docker-update aliases for Docker maintenance.

Export BUN_INSTALL and prepend its bin directory to PATH in .profile.
2026-06-11 15:22:01 +02:00

79 lines
1.8 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
usage() {
echo "Użycie: $0 [OPCJE] [MIN_PORT] [MAX_PORT]"
echo ""
echo "Opcje:"
echo " -n Wypisz też 4 sąsiednie porty (±1, ±2) z ich statusem"
echo " -h Pokaż tę pomoc"
echo ""
echo "Przykłady:"
echo " $0 # zakres 102465535"
echo " $0 3000 9000 # własny zakres"
echo " $0 -n # z sąsiadami"
echo " $0 -n 3000 9000 # z sąsiadami i własnym zakresem"
exit 0
}
SHOW_NEIGHBORS=false
while getopts ":nh" opt; do
case $opt in
n) SHOW_NEIGHBORS=true ;;
h) usage ;;
\?) echo "❌ Nieznana opcja: -$OPTARG" >&2; exit 1 ;;
esac
done
shift $(( OPTIND - 1 ))
MIN_PORT=${1:-1024}
MAX_PORT=${2:-65535}
echo "🔍 Szukam zajętych portów w zakresie $MIN_PORT$MAX_PORT..."
USED_PORTS=$(ss -tuln 2>/dev/null \
| awk 'NR>1 {print $5}' \
| grep -oE '[0-9]+$' \
| sort -un)
USED_COUNT=$(echo "$USED_PORTS" | grep -c '^[0-9]')
echo "📋 Znaleziono $USED_COUNT zajętych portów."
is_used() {
echo "$USED_PORTS" | grep -qx "$1"
}
MAX_ATTEMPTS=1000
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
PORT=$(( RANDOM % (MAX_PORT - MIN_PORT + 1) + MIN_PORT ))
if ! is_used "$PORT"; then
echo ""
echo "✅ Wolny port: $PORT"
if $SHOW_NEIGHBORS; then
echo ""
echo "📊 Sąsiednie porty:"
for OFFSET in -2 -1 1 2; do
NEIGHBOR=$(( PORT + OFFSET ))
if [ $NEIGHBOR -lt 1 ] || [ $NEIGHBOR -gt 65535 ]; then
printf " port %-6s — poza zakresem\n" "$NEIGHBOR"
elif is_used "$NEIGHBOR"; then
printf " port %-6s 🔴 zajęty\n" "$NEIGHBOR"
else
printf " port %-6s 🟢 wolny\n" "$NEIGHBOR"
fi
done
fi
echo ""
exit 0
fi
ATTEMPT=$(( ATTEMPT + 1 ))
done
echo "❌ Nie udało się znaleźć wolnego portu po $MAX_ATTEMPTS próbach."
exit 1