我想创建一个bash脚本来启动服务器,等待服务器启动,然后运行一些代码(由服务器处理),最后再次停止服务器。
这就是我所拥有的,并说明为什么它不起作用:
#!/bin/bash
# Expected: Start the local selenium server and push it to the background.
# Actual: Script continues instantly without waiting for the server to start!
selenium-server -port 4444 &
# Expected: Run the tests, which require the local selenium server to be started
# Actual: Tests fail because the server is not ready.
phpunit tests/ui-tests.php
# Expected: Exiting the process also stops the background job (server).
# Actual: The server continues running interactively in the terminal until stopped via Ctrl-C.
exit
这种脚本的正确(或更好)方法是什么?
答案 0 :(得分:0)
这是我根据markp-fuso的反馈构建的工作脚本:
#!/bin/bash
start_server() {
echo "Start server ..."
selenium-server -port 4444 &
server_pid=$!
# Wait for the server to start (max 10 seconds)
for attempt in {1..10}; do
my_pid=$(lsof -t -i tcp:4444)
if [[ -n $my_pid ]]; then
# Make sure the running server is the one we just started.
if [[ $my_pid -ne $server_pid ]]; then
echo "ERROR: Multiple Selenium Servers running."
echo "→ lsof -t -i tcp:4444 | xargs kill"
exit 1
fi
break
fi
sleep 1
done
if [[ -z $my_pid ]]; then
echo "ERROR: Timeout while waiting for Selenium Server"
exit 1
fi
}
stop_server() {
echo "Stop Server ..."
kill $server_pid
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
start_server
phpunit tests/ui-tests.php
stop_server