shell script automated testing

Preface

        Because the kernel of the Android system is Linux, shell scripts can be executed in the Android system. There are many instructions in adb, our commonly used Android debugging tool, that start with adb shell. This is how adb treats these instructions as shell instructions and executes them in the Android system. So we can write these adb instructions into a shell script, and then execute this script in the Android system, so that the Android system can execute all the instructions in the shell script. If there are loop statements in the script, the instructions in the loop will be executed repeatedly to achieve certain stress testing purposes.

​​​​​​​

Commonly used adb commands

        When using adb, you need to pay attention: when only one mobile phone with the USB debugging function is connected to the current computer, you can directly use the following adb command; when multiple mobile phones with the USB debugging function are connected to the current computer, you need to add after adb The -s parameter specifies the operation of a certain device (except adb devices).

adb ...

adb -s 设备序列号 ...

View device serial number

        Command: adb devices

Reboot the device

        Command: adb reboot

Install and uninstall APP

Install APP

        Instruction: adb install app path (the location where it is stored on the computer)

Uninstall APP

        Command: adb uninstall APP package name to be uninstalled

Get APP package name

        Command: adb shell pm list package -3

        Explanation: adb shell starts with the command, which means executing the shell command; pm is the abbreviation of package manager, this command can perform package-related operations; list package can view all packages on the phone; -3 means APP installed by a third party. We can also use -i to represent the system APP. If no parameters are used, all packages will be output.

Push and get files

Push files

        You can push files from your computer to your phone

        Command: adb push file path on computer and mobile phone path

Get file

        You can push files from your phone to your computer

        Command: adb pull file path on mobile phone computer path

click

        Command: adb shell input tap xy

        Explanation: adb shell is the beginning of the command, indicating the execution of the shell command; input is the input of an event; tap is the click event; Replace x and y in the command. The meaning of the entire command is: input a click event, and the click coordinates are (x, y).

        How to obtain coordinates: Find the version number of the mobile phone system in the system settings , click the version number 7 times in succession to open the developer mode , and check the pointer position option in the developer mode . At this time, when we click on the mobile phone screen, we can see the coordinates of the clicked location.

swipe

        Command: adb shell input swipe x1 y1 x2 y2 time

        Explanation: adb shell is the beginning of the instruction, indicating the execution of the shell instruction; input is the input of an event; swipe is the sliding event; x1 and y1 are the horizontal and vertical coordinates of the starting point, x2 and y2 are the horizontal and vertical coordinates of the end point, and time is the time required for the entire sliding process. Time (controls the speed of sliding, unit ms). The meaning of the entire instruction is: input a sliding event, slide from (x1, y1) to (x2, y2), and the entire sliding process will arrive at (x2, y2) in (x1, y1)time milliseconds at 0 milliseconds.

Long press a point on the screen

        The long press function can be achieved by cleverly using sliding events. When the starting point and end point of the sliding are the same point (x, y), you can keep pressing this point (x, y) for milliseconds.

key(keyevent)

        Command: adb shell input keyevent key

        Explanation: adb shell is the beginning of the command, which means executing the shell command; input is the input of an event; keyevent is the key event; key is the key value. The meaning of the entire command is: input a key event and trigger the event corresponding to the key whose key value is key.

adb common key value table

Chinese name key value Chinese name key value Chinese name key value Chinese name key value
Button Home 3 Navigation key OK 23 Key 'N' 42 Notification key 83
return key 4 Volume up key 24 Button 'O' 43 search key 84
dial key 5 Volume down key 25 Button 'P' 44 Microphone mute button 91
On-hook key 6 Power button 26 Button 'Q' 45 Page up key 92
Key '0' 7 Photo button 27 Button 'R' 46 Page down key 93
Button '1' 8 Button 'A' 29 Button 'S' 47 ESC 111
Button '2' 9 Button 'B' 30 Key 'T' 48 Delete key 112
Button '3' 10 Button 'C' 31 Button 'U' 49 caps lock key 115
Button '4' 11 Button 'D' 32 Button 'V' 50 scroll lock key 116
Button '5' 12 Button 'E' 33 Button 'W' 51 Break/Pause key 121
Button '6' 13 Key 'F' 34 Button 'X' 52 Cursor moves to start 122
Button '7' 14 Button 'G' 35 Button 'Y' 53 Cursor moves to the end 123
Button '8' 15 Button 'H' 36 Button 'Z' 54 Insert key 124
Button '9' 16 Button 'I' 37 Tab key 61 keypad lock 143
Navigation key up 19 Button 'J' 38 Enter key 66 Speaker mute button 164
Navigation key down 20 Key 'K' 39 backspace key 67 magnify key 168
Navigation key left 21 Button 'L' 40 Photo focus button 80 Zoom out key 169
Navigation key right 22 Button 'M' 41 Menu key 82 task key 187

Get special buttons developed by yourself

        When we encounter some Android devices with self-developed special buttons, how to get the key value of this special button. If you know the developer, you can ask the developer; if you don't know the developer, you can try the following command to get it.

        Command: adb shell "logcat |grep "keycode""

        Explanation: adb shell is the beginning of the command, which means executing the shell command; logcat is to obtain the system log; | is to filter the pipe symbol; grep "keycode" is to find the line containing the string "keycode".

        Usage: After entering the above command in the computer terminal, press the special button on the Android device (be careful not to touch the touch screen and other buttons) to get the key value. If no information is output, you can only ask the developer.

Simulate keystrokes (sendevent)

        Simulated buttons are only valid for systems below Android 10. After Android 10, Google prohibits the use of sendevent simulated buttons for security reasons. The simulated buttons here truly simulate the effect of pressing buttons with your hands. The buttons above just send events that will be triggered by pressing the button. For example, the above buttons can turn on and off the screen by pressing the power button, but you cannot press and hold the power button to pop up the shutdown button. The simulated button here will do.

Get key event

        Command: adb shell getevent -c 4

        Explanation: adb shell is the beginning of the command, which means executing the shell command; getevent is to obtain the key event; -c 4 is to return immediately after obtaining the previous 4 lines of information.

        Usage: After entering the above command in the computer terminal, press the key to be simulated on the Android device (be careful not to touch the touch screen and other keys) to get the key event. The following 4 lines of information are obtained by pressing the volume + key.

/dev/input/event1: 0001 0073 00000001
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0001 0073 00000000
/dev/input/event1: 0000 0000 00000000

Among the four lines of information above, the first two lines indicate pressing the volume + key; the last two lines indicate lifting the volume + key. Among them, 0073 represents the key value of volume +. This is not the same thing as the key value of adb, so be careful to distinguish it. 0073 is a hexadecimal number. It needs to be converted to a decimal number. The converted decimal number is 0115.

Send key events (simulate key presses)

        The command to simulate long pressing the volume + key is as follows (executed in adb shell):

sendevent /dev/input/event1 0001 0115 00000001
sendevent /dev/input/event1 0000 0000 00000000
sleep 1
sendevent /dev/input/event1 0001 0115 00000000
sendevent /dev/input/event1 0000 0000 00000000

In the five lines of instructions above, the first two lines mean pressing the volume + key; the last two lines mean lifting the volume + key, and the sleep 1 in the middle means pressing the volume key and then stopping for 1 second, that is, holding it down for 1 second. Lift the volume + button again. This achieves the effect of long pressing the volume + key.

Open APP

        Each APP will have a main activity. We only need to start this main activity to open the APP. First we need to get the main activity of this APP, and then start the main activity through the adb command to open the APP.

Get activity

        指令:adb shell "dumpsys window | grep mCurrentFocus"

        Explanation: adb shell is the beginning of the command, which means executing the shell command; dumpsys is to query the running status of the system service; window is to obtain the current interface information of the mobile phone; | is to filter the pipe symbol; grep is the filtering command of Linux, | grep mCurrentFocus is to filter out the characters containing String mCurrentFocus row.

        Usage: We first open an APP on the mobile phone, and then execute the adb command above, we can get the current activity information of the APP. For example: when we open Google Chrome on our mobile phone and execute the above adb command, we can get the following information.

  mCurrentFocus=Window{b07d5d u0 com.android.chrome/com.google.android.apps.chrome.Main}-[Surface(name=*Title#569)/@0x2b077cd]

Among them, com.android.chrome/com.google.android.apps.chrome.Main is the activity we need.

Start activity

        Command: adb shell am start -S -n activity

        Explanation: adb shell is the beginning of the command, indicating the execution of the shell command; am is the abbreviation of activity manager, this command can simulate system behavior; start is the command to start the activity; -S is to close the APP process to which the activity belongs and then start the activity (commonly known as cold start ); -n specifies the name of the activity to be started. You can do it without adding -S. Without adding -S, you can also find out whether there is a memory leak in the APP.

        Usage: After we obtain the main activity of an APP, we use the above instructions to directly start the activity. For example: we can use adb shell am start -n com.android.chrome/com.google.android.apps.chrome.Main to start Google Chrome.

Repeated cold start of APP

        指令:adb shell am start -S -R times -W activity

        Explanation: adb shell is the beginning of the command, indicating the execution of the shell command; am is the abbreviation of activity manager, this command can simulate system behavior; start is the command to start the activity; -S is to close the APP process to which the activity belongs and then start the activity (commonly known as cold start ); -R is the repeat startup command, times is the number of repetitions, if you want to repeatedly launch the APP how many times, replace times with a number; -W is the command to wait for the APP startup to complete, and the startup time will be output after the APP startup is completed.

Repeated hot start of APP

        Directive: adb shell am start -R times -W activity

        Explanation: A cold start without adding the -S parameter is a hot start.

dial number

        Instruction: adb shell am start -a android.intent.action.CALL -d tel:10086

        Explanation: adb shell is the beginning of the instruction, indicating the execution of the shell instruction; am is the abbreviation of activity manager, this instruction can simulate system behavior; start is the startup activity instruction; -a is to send a broadcast instruction; android.intent.action.CALL is to make a call Broadcast; -d is the specified parameter command; tel:10086 is the dialed phone number 10086.

open the Web page

        指令:adb shell am start -a android.intent.action.VIEW -d http://www.baidu.com

        Explanation: adb shell is the beginning of the instruction, indicating the execution of the shell instruction; am is the abbreviation of activity manager, this instruction can simulate system behavior; start is the startup activity instruction; -a is to send a broadcast instruction; android.intent.action.VIEW is based on data Type opens the Android default application broadcast; -d is the specified data command; http://www.baidu.com is the url address of the opened page.

play video

        Command: adb shell am start -a "android.intent.action.VIEW" -t "video/*" -d "file:///storage/sdcard0/Movies/Ice Age.mp4"

        Explanation: adb shell is the beginning of the instruction, indicating the execution of the shell instruction; am is the abbreviation of activity manager, this instruction can simulate system behavior; start is the startup activity instruction; -a is to send a broadcast instruction; android.intent.action.VIEW is based on data Type opens the Android default application broadcast; -t is the specified application type; video/* is the application type; -d is the specified parameter instruction; file:///storage/sdcard0/Movies/Ice Age.mp4 is the video Ice Age.mp4 file path. You can also use -n to specify a specific application, and -t is not needed to specify the application type.

play music

        指令:adb shell am start -a "android.intent.action.VIEW" -t "audio/mp3" -d "file:///storage/sdcard0/Music/nomy.mp3"

        Explanation: adb shell is the beginning of the instruction, indicating the execution of the shell instruction; am is the abbreviation of activity manager, this instruction can simulate system behavior; start is the startup activity instruction; -a is to send a broadcast instruction; android.intent.action.VIEW is based on data Type opens the Android default application broadcast; -t is the specified application type; audio/mp3 is the application type; -d is the specified parameter command; file:///storage/sdcard0/Music/nomy.mp3 is the file path of music nomy.mp3 . You can also use -n to specify a specific application, and -t is not needed to specify the application type.

Get screen element information

        Command: adb shell uiautomator dump

        Explanation: adb shell is the beginning of the command, which means executing the shell command; uiautomator is the system operation UI element module; dump is the command to output UI interface information.

        Usage: After executing the above command, you will get an xml file (/sdcard/window_dump.xml). We use adb pull to push it to the computer, and then we can use python to analyze it (xml.etree.ElementTree).

Screen always on setting

Turn on and keep on

        Command: adb shell svc power stayon true

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; power stayon is the screen always-on related operation command; true is the enable command.

Turn off and stay on

        Command: adb shell svc power stayon false

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; power stayon is the screen always-on related operation command; false is the shutdown command.

Always on when USB is plugged in

        Directive: adb shell svc power stayon usb

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; power stayon is the screen always-on related operation command; usb is the keep-on command when the USB is inserted.

Always on when plugged in

        Command: adb shell svc power stayon ac

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; power stayon is the screen always-on related operation command; ac is the stay-on command when the power is plugged in.

Turn WiFi on and off

Turn on WiFi

        Command: adb shell svc wifi enable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; wifi is the Wifi related operation command; enable is the startup command.

Turn off WiFi

        Command: adb shell svc wifi disable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; wifi is the Wifi related operation command; disable is the shutdown command.

Switch data flow

Turn on data traffic

        Command: adb shell svc data enable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service-related command; data is the Data-related operation command; enable is the startup command.

Turn off data traffic

        指令:adb shell svc data disable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service-related command; data is the Data-related operation command; disable is the shutdown command.

Turn Bluetooth on and off

Turn on Bluetooth

        Command: adb shell svc bluetooth enable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; bluetooth is the Bluetooth related operation command; enable is the startup command.

Turn off Bluetooth

        Command: adb shell svc bluetooth disable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; bluetooth is the Bluetooth related operation command; disable is the shutdown command.

Switch NFC

Turn on NFC

        Command: adb shell svc nfc enable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; nfc is the NFC related operation command; enable is the startup command.

Turn off NFC

        指令:adb shell svc nfc disable

        Explanation: adb shell is the beginning of the command, which means executing the shell command; svc is the system service related command; nfc is the NFC related operation command; disable is the shutdown command.

Screen capture and recording

screenshot

        Take screenshots on your phone and store them in your phone’s storage memory

        Command: adb shell screencap -p /sdcard/xxx.png

        Explanation: adb shell is the beginning of the command, which means executing the shell command; screencap is the screenshot command; -p is the specified storage location; /sdcard is the root directory of the mobile phone storage memory; xxx.png is the png picture named xxx.

Record screen

        Record the screen on your phone and store it in your phone’s memory

        Command: adb shell screenrecord /sdcard/xxx.mp4

        Explanation: adb shell is the beginning of the command, which means executing the shell command; screenrecord is the screen recording command; /sdcard is the root directory of the mobile phone storage memory; xxx.mp4 is the mp4 video named xxx.

Get current running memory usage

Total running memory usage of mobile phone

        Command: adb shell "dumpsys meminfo | grep Used"

        Explanation: adb shell is the beginning of the command, which means executing the shell command; dumpsys is to query the running status of the system service; meminfo is to query all the information of the memory; | is to filter the pipe symbol; grep is the Linux filtering command; Used is the string specifying the filter. | grep Used generally filters out lines containing the string Used.

Memory usage of a single APP running 

        Command: adb shell "dumpsys APP package name | grep PSS | awk '{print $3}'"

        Explanation: adb shell is the beginning of the instruction, which means executing the shell instruction; dumpsys is to query the running status of the system service; meminfo is to query all the information of the memory; | is to filter the pipe symbol; grep is the Linux filtering instruction; PSS is the string to specify the filter; awk It is a linux column filtering command; '{print $3}' is to print out the data in column 3; | grep PSS | awk '{print $3}' is generally to filter out the data in column 3 in the row containing the string PSS, and print it out.

Get phone screen size

        Command: adb shell wm size

        Explanation: adb shell is the beginning of the command, which means executing the shell command; wm is the abbreviation of window manager, which is the command related to screen management; size is the command to return the screen size.

Get the on and off status of mobile phone screen

        指令:adb shell "dumpsys display | grep mScreenState"

        Explanation: adb shell is the beginning of the command, which means executing the shell command; dumpsys is to query the running status of the system service; display is to display relevant information on the screen; | is the filter pipe symbol; grep is the Linux filter command; mScreenState is the string specifying the filter; | grep mScreenState generally filters out rows containing the string mScreenState.

On and off screen

Bright screen

        Command: adb shell input keyevent 224

        Explanation: adb shell is the beginning of the command, which means executing the shell command; input is the input of an event; keyevent is the key event; 224 is the key value. The overall meaning is to input the bright screen event.

Turn off the screen

        Command: adb shell input keyevent 223

        Explanation: adb shell is the beginning of the command, which means executing the shell command; input is the input of an event; keyevent is the key event; 223 is the key value. The overall meaning is to enter the screen off event.

View battery information

        Command: adb shell dumpsys battery

        Explanation: adb shell is the beginning of the command, which means executing the shell command; dumpsys is to query the running status of the system service; battery is the battery information. After executing this command, we can get the charging status, battery power, battery temperature, battery voltage and other information.

reset

        Google provides instructions for restoring factory settings for stress testing in versions of Android 10 and above. This instruction will prohibit some customized functions of the Android system by various manufacturers. Therefore, after using this command to restore factory settings, there will be no boot wizard, no screen lock, and the USB debugging function will be turned on. So we can use this command continuously to perform a stress test on the phone to restore factory settings.

        指令:adb shell cmd testharness enable

shell script

        To write shell scripts, we need to first understand some basic shell syntax. Here we only briefly introduce the syntax of shell scripts. Through these simple introductions, we are enough to write automated test scripts for mobile phones. If you want to know more about shell scripts, you can search for shell scripts in CSDN , and you will definitely find a more detailed introduction.

variable

Ordinary variables

        Assign values ​​to variables directly, and be sure not to leave spaces on both sides of the = sign (I write a lot of python, so I always leave spaces in the habit, but I found that an error was reported, and it took me a long time to find the reason).

name='小明'
age=18

command variables

        After executing the shell command, assign the returned result to the variable. The command variable can be written in the following two ways.

# 得到手机屏幕亮灭状态
screenState=`dumpsys display | grep mScreenState`
# 得到手机屏幕大小
winSize=$(wm size)

Get the value of a variable

        There are four ways to view the value of a variable: $variable, "$variable", ${variable}, "${variable}". Among them, ${variable} and "${variable}" have special usage, which can intercept part of the value of the variable: ${variable: starting position}, ${variable: starting position: intercepting length}.

screenState=$(dumpsys display | grep mScreenState)
echo screenState             # screenState
echo $screenState            # mScreenState=OFF
echo "$screenState"          #   mScreenState=OFF
echo ${screenState}          # mScreenState=OFF
echo ${screenState:15:3}     # OFF
echo "${screenState}"        #   mScreenState=OFF
echo "${screenState:15}"     # OFF

        The echo command is a print output command in Linux. This command uses the redirection symbols > (overwrite) and >> (append) to write the output content into a text.

test statement

        The function of the test statement is to determine whether a conditional expression is true. If it is true, it returns 0, if not, it returns 1. There are two ways to write test statements:

Writing method one

[ 1 = 2 ]  # 1

Writing method two

test 1 = 1  # 0

The returned 0 may not be displayed in the command terminal, but it does not affect that it does return 0.

Compare numerical values

-eq Determine whether the left and right sides are equal
- is Determine whether the left and right sides are not equal
-gt Determine whether the left side is greater than the right side
-lt Determine whether the left side is smaller than the right side
-ge Determine whether the left side is greater than or equal to the right side
- the Determine whether the left side is less than or equal to the right side

        We use the above test statement for demonstration.

[ 1 -eq 1 ]  # 0
[ 1 -ne 2 ]  # 0
[ 2 -gt 1 ]  # 0
[ 1 -lt 2 ]  # 0
[ 1 -ge 1 ]  # 0
[ 2 -ge 1 ]  # 0
[ 1 -le 1 ]  # 0
[ 1 -le 2 ]  # 0

Numerical calculations (let)

        The let instruction can perform four arithmetic operations on integers.

number=1
let number2=number+1
echo $number2           # 2
let number3=number2*3
echo $number3           # 6
let number4=number3/2
echo $number4           # 3
let number5=number4-1
echo $number5           # 2

        let also supports +=, -=, *=, /= assignment operators.

number=1
let number+=1
echo $number   # 2
let number-=1
echo $number   # 1
let number*=3
echo $number   # 3
let number/=3
echo $number   # 1

string

Determine whether they are equal

== Determine whether the strings on the left and right sides are equal
!= Determine whether the left and right strings are not equal

        The test statement is also used here to demonstrate to everyone. Now my phone is in the screen off state.

screenState=$(dumpsys display | grep mScreenState)
echo ${screenState:15:3}           # OFF
[ ${screenState:15:3} == 'OFF' ]   # 0
screenState=$(dumpsys display | grep mScreenState)
echo ${screenState:15:3}           # OFF
[ ${screenState:15:3} != 'OFF' ]   # 1

The length of the output string

        ${#string} can output the length of the string.

string='abcde'
echo ${#string}  # 5

Applications of arrays

        Arrays are supported in bash. The separators between elements in the array are spaces, and only one-dimensional arrays are supported, and multi-dimensional arrays are not supported. Arrays support indexing. The index subscript of the first element is 0, and the index subscripts of subsequent elements increase in sequence.

keylist=(3 4 5 6 7)
echo "home键是:${keylist[0]}"  # home键是:3
echo "back键是:${keylist[1]}"  # back键是:4

         Viewing all elements at once can be achieved using * and @.

keylist=('hello' 'world' 1 2 3)
echo "所有元素:${keylist[*]}"     # 所有元素:hello world 1 2 3
echo "所有元素:${keylist[@]}"     # 所有元素:hello world 1 2 3
#  结合#号可以得到数组的长度(元素个数)
keylist=('hello' 'world' 1 2 3)
echo "数组长度为:${#keylist[*]}"  # 数组长度为:5
echo "数组长度为:${#keylist[@]}"  # 数组长度为:5

        We can modify the value of the corresponding element in the array through the index subscript.

keylist=(3 4 5 6 7)
keylist[3]=187
echo "任务键是:${keylist[3]}"  # 任务键是:187

        When the element corresponding to the index subscript does not exist, a new element is added.

keylist=('hello' 'world' 1 2 3)
echo "所有元素:${keylist[*]}"  # 所有元素:hello world 1 2 3
keylist[5]='haha'
echo "所有元素:${keylist[@]}"  # 所有元素:hello world 1 2 3 haha
keylist[6]='xixi'
echo "所有元素:${keylist[*]}"  # 所有元素:hello world 1 2 3 haha xixi

        We can delete an element in the array or delete the entire array through the unset instruction.

keylist=('hello' 'world' 1 2 3)
echo "所有元素:${keylist[*]}"  # 所有元素:hello world 1 2 3
unset keylist[0]
echo "所有元素:${keylist[@]}"  # 所有元素:world 1 2 3
unset keylist
echo "我无了:${keylist[*]}"    # 我无了:

 if judgment statement

basic structure

if [ 条件 ]
then
    满足条件时要执行的语句(缩进一个Tab键或4个空格)
else
    不满足条件时要执行的语句
fi

        If is followed by a test statement, first determine whether the value returned by the test statement after if is 0. If it is 0, the statement below then will be executed, and if it is 1, the statement below else will be executed. for example:

value='hello'

if [ 1 -gt 2 ]
then
	value='1 大于 2'
else
	value='1 不大于 2'
fi

echo "判断结果:$value"  # 判断结果:1 不大于 2

        When we do not need to execute the statement below else, we can omit the else statement.

value='hello'

if [ 1 -gt 2 ]
then
	value='1 大于 2'
fi

echo "判断结果:$value"  # 判断结果:hello

multi-condition structure

if [ 条件1 ]
then
    满足条件1时要执行的语句(缩进一个Tab键或4个空格)
elif [ 条件2 ]
then
    满足条件2时要执行的语句
elif [ 条件3 ]
then
    满足条件3时要执行的语句
.
.
.
elif [ 条件n ]
then
    满足条件n时要执行的语句
else
    不满足所有条件时要执行的语句
fi

        The multi-condition structure has more elif statements than the basic structure. elif can be added infinitely until all our judgment conditions are added. First, judge condition 1. When condition 1 is true, execute the statement to be executed when condition 1 is met and then end the if statement; when condition 1 is not true, judge condition 2. When condition 2 is true, execute the statement to be executed when condition 2 is met and end the if statement; condition When 2 is not true, condition 3 is judged, and so on; when all conditions are not true, the statement below else is executed. For example, let's grade primary school students' math scores. Those with scores greater than or equal to 90 are considered excellent, scores greater than or equal to 80 are good, scores greater than 60 are average, scores equal to 60 are passing, and scores less than 60 are considered poor. Passed.

score=85
level='未评级'

if [ score -ge 90 ]
then
	level='优秀'
elif [ score -ge 80 ]
then
	level='良好'
elif [ score -gt 60 ]
then
	level='普通'
elif [ score -eq 60 ]
then
	level='及格'
else
	level='不及格'
fi

echo "成绩 $score 对应的评级为:$level"  # 成绩 85 对应的评级为:良好

pause statement

        The sleep instruction allows an execution interval between the upper and lower lines of statements.

input keyevent 223
sleep 1
input keyevent 224

First execute input keyevent 223 to turn off the phone screen, pause for 1 second and then execute input keyevent 224 to turn on the phone screen.

loop statement

for loop statement

        There are two ways to use the for loop statement. The first one is similar to the for loop statement in Python. The second one is similar to the for loop in Java, JavaScript, and C++ (this method is not suitable for Android systems and can be ignored directly).

for i in var1 var2 var3 . . . . varn
do
    每次循环要执行的语句
done

        The first loop assigns the value of var1 to variable i, the second loop assigns the value of var2 to variable i, and so on until the value of varn is assigned to variable i, ending the loop. for example:

number_list=(1 2 3 4 5)
number_sum=0

for i in ${number_list[*]}  # for i in 1 2 3 4 5
do
	let number_sum+=i
done

echo $number_sum  # 15

while loop statement

        The while loop statement loops by judging whether the condition is true or false. When the condition is true, the loop statement is executed, and when the condition is false, the loop ends.

while ((条件))
do
    每次循环要执行的语句
done

        Note that the conditional comparison symbols in (()) use ==, !=, <, >, <=, >=, which should be distinguished from test statements. for example:

number=0

while ((number<10))
do
	let number+=1
done

echo $number  # 10

        Infinite loops can use conditions that are always true such as: ((1==1)), ((1)), or use true directly.

while true
do
	echo "hello world"
	sleep 1
done

The above code will always print hello world, printing every 1 second.

continue

        This loop will end when the continue statement is executed, and the code after continue will not be executed. continue is used in the same way as in the for loop and the while loop, and the effect is the same.

number=0
number_sum=0

while ((number<10))
do
	let number+=1
	if [ number -gt 5 ]
	then
		continue
	fi
	let number_sum+=number
done

echo $number_sum  # 15

When number > 5, continue will be executed. When continue is executed, the current loop will end and enter the next loop, so let number_sum+=number will not be executed, so the value of number_sum after the loop ends is 1+2+3 +4+5=15.

break

        When the break statement is executed, the loop will be ended directly without proceeding to the next loop. break is used in the same way as in the for loop and the while loop, and the effect is the same.

number_sum=0

for i in 1 2 3 4 5 6 7 8 9 10
do
	let number_sum+=i
	if [ i -gt 5 ]
	then
		break
	fi
done

echo $number_sum  # 21

When i > 5, break will be executed. When break is executed, the loop will end directly. At this time, the value of number_sum is 1+2+3+4+5+6=21.

define function

        Bash also supports function encapsulation. We can encapsulate some frequently used procedural statements into a function. The position where the function is defined in the shell script must be before the position where the function is used, otherwise there will be an error of undefined function.

basic structure

# 无参函数
函数名(){
    函数内的语句
}
# 无参函数使用方式
函数名

# 有参函数
函数名(){
    函数内的语句(内有参数$1、$2的使用)
}
# 有参函数使用方式
函数名 值1 值2

function without parameters

        Functions that do not need to be passed in parameters can be called directly using the function name.

my_print(){
    echo "hello world"
}

my_print  # hello world

function with parameters

        For functions that need to pass in parameters, $1, $2...$n is used inside the function to represent the first, second to nth parameters. The calling method is the function name plus the value to be passed (separated by spaces).

my_info(){
	echo "我叫:$1 今年:$2 岁"
}

my_info '小明' 18  # 我叫:小明 今年:18 岁

RANDOMrandom number

        RANDOM is a built-in function in bash used to generate random numbers. Using RANDOM can generate a random number between 0 and 32767.

echo $RANDOM  # 19568
echo $RANDOM  # 27608
echo $RANDOM  # 569

        You can use $((RANDOM%number)) and $((RANDOM%number+number)) to specify the range of random numbers.

        The writing method for generating random numbers in the range of 0~9 is as follows:

echo $((RANDOM%10))  # 3

The starting value of RANDOM is 0, and the ending value can be customized, but RANDOM cannot get the ending value.

        The writing method for generating random numbers in the range of 10~20 is as follows:

echo $((RANDOM%11+10))  # 15

The random number originally generated by $(()RANDOM%11) is a number between 0 and 10, but if we add 10 after this number, it becomes a number between 10 and 20.

        Have you ever thought that we use RANDOM + array + loop + key command to make the phone press random keys continuously.

keylist=(3 4 187)  # 定义要随机按键的键值数组

while true
do
    key=${keylist[$((RANDOM%3))]}  # 用0~2中的随机下标取出一个键值
    input keyevent key  # 发送按键事件
    sleep 2
done

shell automated test script

        With the above basic knowledge, we can write automated test scripts. Among the adb instructions, all instructions starting with adb shell can be placed in the shell script. The premise is that the adb shell is removed and only the part after the adb shell is removed.

Write automated test scripts

        Now let's write a shell script that turns the screen on and off repeatedly.

while true
do
	input keyevent 223
	sleep 2
	input keyevent 224
	sleep 2
done

        Write a shell script that continuously enters and exits Google Chrome. After opening Google Chrome, determine whether there is a crash and write the test log to the storage memory of the phone.

activity='com.android.chrome/com.google.android.apps.chrome.Main'
count=1
while true
do
    am start -n $activity
    sleep 3
	info=$(dumpsys window | grep mCurrentFocus | awk '{print $3}')
	package=${info:0:${#activity}}
	if [ $package == $activity ]
	then
		echo "第 $count 次打开谷歌浏览器,打开成功" >> /sdcard/ChromeTest.txt
	else
		echo "第 $count 次打开谷歌浏览器,打开失败---------" >> /sdcard/ChromeTest.txt
	fi
	input keyevent 4
	sleep 2
	let count+=1
done

        I have given two examples. You can combine the above knowledge points to write automated test scripts according to your testing needs. If you know python or C++, you can try making a quick scripting tool. Python can use the tkinter framework or the pyside6 framework. For lightweight tools, tkinter is best, and C++ can use the QT framework.

Execute automated test scripts

        I will use the test script ChromeTest.sh in the current folder as a column to demonstrate the execution process of the script.

Push test script to mobile phone

        Command: adb push ChromeTest.sh /data/local/tmp

        Explanation: Use the adb command to push the shell script we wrote to the /data/local/tmp directory of the mobile phone.

Modify script format

        If our script is written on Windows, the format of the script file must be converted to Unix format. If you are writing on Linux please ignore this command.

        Command: adb shell "dos2unix /data/local/tmp/ChromeTest.sh"

        Explanation: Use the dos2unix command to convert the format of the ChromeTest.sh file to Unix format.

grant execute permission

        Command: adb shell "chmod 777 ChromeTest.sh"

        Explanation: Use the chmod command to grant read, write, and execute permissions to the file ChromeTest.sh.

Execute script

        Command: adb shell "nohup ./data/local/tmp/ChromeTest.sh > /dev/null &"

        Explanation: Use the nohup command to make our script run in the background. >/dev/null means that the output of the script is redirected to the /dev/null folder, & means to run offline. After using & we unplug the USB cable, the shell script will continue to run on the phone.

End automated test script

        If we want to end the shell script running on the phone early, there are two ways to do it. The first method is to shut down or restart directly, and the second method is to use the kill command to end the shell script.

Get shell script process ID

        Command: adb shell "ps | grep sh$ | awk '{print $2}'"

        Explanation: Use the ps command to view all process information on the phone; use grep to filter out lines ending with sh; use awk to print out the data in the second column.

        Through the above instructions we can get at least two process numbers. There is a system shell process, and its process number changes at any time and we have no way to end it; there is a shell script process, and we can use the kill command to end it. So we can use the kill command on both process numbers. Anyway, we cannot end the system's shll process.

End shell script process

        Command: adb shell "kill PID"

        Explanation: Use the kill command to forcefully end the process; PID is the process number to be terminated.

suggestion

        If you know python or C++, I suggest you write a tool with a UI interface to execute the shell script and end the shell script, and encapsulate the above instructions. Selecting the shell script file through the UI interface and clicking the button to execute it is much more convenient than executing instructions one by one.

Guess you like

Origin blog.csdn.net/qq_40148262/article/details/131190445