android手机测试shell脚本常用问答
目录
Q:如果我测试完某个操作,想查询logcat中包含不同的关键字,比如A and B and C且这3个不在同一行
Q:我想提前结束脚本使用ctrl+C,但是我又想比如收集log,清理等工作在shell如何实现
Q:如果我测试完某个操作,想查询logcat中包含不同的关键字,比如A and B and C且这3个不在同一行
A:
function wait_for_logcat {
local device_serial="$1"
local timeout_sec="$2"
local start_time=$(date +%s)
local a_found=false
local b_found=false
local c_found=false
while [ $(($(date +%s) - $start_time)) -lt $timeout_sec ]; do
local logcat_output=$(adb -s "$device_serial" logcat -d)
if echo "$logcat_output" | grep -q "A"; then
a_found=true
fi
if echo "$logcat_output" | grep -q "B"; then
b_found=true
fi
if echo "$logcat_output" | grep -q "C"; then
c_found=true
fi
if [ "$a_found" = true ] && [ "$b_found" = true ] && [ "$c_found" = true ]; then
echo "Found A, B, and C in logcat output"
return 0
fi
echo "Waiting for A, B, and C in logcat output..."
sleep 5
done
echo "Unable to find A, B, and C in logcat output within $timeout_sec seconds"
return 1
}
wait_for_logcat yourSerial 60
Q:等待机器连接,如果连接不上超时返回
A:
function wait_for_device {
local device_serial="$1"
local timeout_sec="$2"
local start_time=$(date +%s)
while [ $(($(date +%s) - $start_time)) -lt $timeout_sec ]; do
if adb devices | grep -wq "$device_serial"; then
echo "Device $device_serial is available"
return 0
fi
echo "Waiting for device $device_serial to become available..."
sleep 5
done
echo "Device $device_serial did not become available within $timeout_sec seconds"
return 1
}
wait_for_device YourDevice 300
# most like adb wait-for-device
Q:我想提前结束脚本使用ctrl+C,但是我又想比如收集log,清理等工作在shell如何实现
A:
# ctrl+c to cleanup
function cleanup {
echo "Cleaning up..."
# do cleanup tasks
exit 0
}
trap cleanup INT
# your script code here
Q:我想实时的后台查询logcat,并且查询到了调用一个函数(callback) 在函数中调用响应操作,比如查询有界面弹出,可以消除弹出框,这个有很多用途,比如log查询到一个错误,可以将log开关打开抓到更多的log
A:
function CALLBACK_FUNCTION {
# your call back function here
}
function search_logcat {
local device_serial="$1"
local search_pattern="$2"
local callback_function="$3"
adb -s "$device_serial" logcat | grep --line-buffered "$search_pattern" | while read -r line; do
echo "$line"
$callback_function # call the specified function when the search pattern is found
done &
}
search_logcat YOUR—DEVICE "SEARCH_PATTERN" "CALLBACK_FUNCTION"
Q:我的函数经常超时或卡住不动,如何限定timeout退出
A:
function YOUR_COMMAND_HERE {
# your function here, but this function may stuck for sometimes
}
function execute_with_timeout {
local timeout_sec="$1"
shift
local command="$@"
local start_time=$(date +%s)
bash -c "$command" &
local pid=$!
while [ $(($(date +%s) - $start_time)) -lt $timeout_sec ]; do
if ps -p $pid > /dev/null; then
# command still running
sleep 1
else
# command finished
wait $pid
return $?
fi
done
# command took too long to execute, kill it and return an error
kill "$pid" &> /dev/null
echo "Command exceeded timeout of $timeout_sec seconds"
return 1
}
execute_with_timeout 30 "YOUR_COMMAND_HERE"