实际上我的脚本存在于路径下/home/user/bin/script.sh
,当我运行名为 script.sh 的上述脚本时,该脚本将在 Firefox 网页中显示 html 文件。
但问题是,当我从包含此 html 文件的目录运行此脚本时,它可以正常工作,但从任何其他目录运行它都不起作用。用于运行脚本的命令是:
/path/to/script.sh /path/to/html file
此外,当我从任何其他目录运行脚本时,网页会显示该特定目录的内容。假设我从目录 /home 运行命令/user/Manu/archave
,它会在网页中显示此 archave 目录的内容。请查找 script.sh 文件的内容
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 /home/egajash/arch/index.html"
exit 1
fi
HTML_PATH="$1"
PORT_FILE=".chosen_port"
function find_free_port() {
for port in {8100..8110}; do
if ! nc -z -v -w5 localhost $port 2>/dev/null; then
echo $port
return
fi
done
}
if [ -e "$PORT_FILE" ]; then
PORT=$(cat "$PORT_FILE")
fi
if [ -z "$PORT" ] || nc -z -v -w5 localhost "$PORT" 2>/dev/null; then
PORT=$(find_free_port)
echo "$PORT" > "$PORT_FILE"
fi
function stop_server() {
local port="$1"
local pid=$(lsof -t -i:$port)
if [ -n "$pid" ]; then
kill "$pid"
fi
}
function monitor_browser() {
local browser_pid
while true; do
browser_pid=$(pgrep -f "Firefox.*$PORT")
if [ -z "$browser_pid" ]; then
echo "Web browser closed. Exiting..."
stop_server "$PORT"
exit
fi
sleep 1
done
}
stop_server "$PORT"
if [[ -n $PORT ]]; then
python3 -m http.server $PORT &
firefox "http://localhost:$PORT" &
echo "Server is running on port $PORT. This script will automatically close when the web browser is closed."
monitor_browser
else
echo "No free port available."
fi