shell

October 22, 2022

shell

The shell is the Unix Shell, which provides a series of commands for interacting with the operating system in Unix-like systems.

Many programs can be used to execute shell commands, such as terminal emulators.

In CloudControl it is roughly equivalent to executing the command "adb shell" with adb. Its realization includes two ways:

  • Executed by java.lang.Runtime.exec (shell, Tap, Home and other functions)
  • Executed through the embedded terminal emulator (RootAutomator, Shell, etc.)

Stability: 2 - Stable

shell(cmd[, root])

  • cmd {string} The command to execute
  • root {Boolean} Whether to run with root privileges, the default is false.

Execute the command cmd once, and return the execution result of the command. The properties of the returned object are as follows:

  • code {number} Return code. It is 0 when the execution is successful, and a non-zero number when it fails.
  • result {string} Running result (stdout output result)
  • error {string} The error message of the operation (stderr output result). For example, executing a command that requires root privileges but does not grant root privileges will return the error message "Permission denied".

Example (forcibly stop WeChat):


//var result = shell("am force-stop com.tencent.mm", { adb: true }); //Run with adb privileges                 
var result = shell("am force-stop com.tencent.mm", true);//Run with root privileges 
log(result);
console. show();
if(result. code == 0){
   toastLog("executed successfully");
}else{
   toastLog("Execution failed! Please go to the console to view the error message");
}

Shell

Stability: 2 - Stable

Shell functions are used to execute a single command at one time and get the result. If multiple commands need to be executed, it is more efficient to use the Shell object. This is because, each time a shell function is run, a separate shell process will be opened and closed after the operation is over. This process takes a certain amount of time; and the Shell object uses the same shell process from beginning to end.

new Shell(root)

  • root {Boolean} Whether to run a shell process with root privileges, the default is false. This will affect the permissions of subsequent commands executed using the Shell object

The "constructor" of the Shell object.


//var sh = new Shell({ adb: true }); //Run with adb privileges
var sh = new Shell(true);//Run with root privileges
//Forcibly stop WeChat
sh.exec("am force-stop com.tencent.mm");
sh. exit();

Shell.exec(cmd)

  • cmd {string} The command to execute

Execute the command cmd. This function does not return any value.

Note that command execution is "asynchronous", non-blocking. That is, it will not wait for the command to complete before continuing to execute downwards.

Although such a design is inconvenient to use, it is limited by the terminal emulator and there is no solution for the time being; if a solution can be found later, the Shell.execAndWaitFor function will be provided.

Shell. exit()

Exit the shell directly. The command being executed will be forced to quit.

Shell. exitAndWaitFor()

Execute the "exit" command and wait for the execution of the command to complete and exit the shell.

This function executes the exit command to exit the shell normally.

Shell.setCallback(callback)

  • callback {Object} callback function

Set the callback function of the shell to monitor the output of the shell. Can include the following attributes:

  • onOutput {Function} This function will be called whenever the shell has new output. Its argument is a string.
  • onNewLine {Function} This function will be called whenever the shell has a new line of output. Its argument is a string (not including the final newline).

E.g:

var sh = new Shell();
sh.setCallback({
onNewLine: function(line){
//Print to the console when there is a new line of output
log(line);
}
})
while(true){
//Loop through commands
var cmd = dialogs.rawInput("Please enter the command to be executed, enter exit to exit");
if(cmd == "exit"){
break;
}
	//Excuting an order
sh.exec(cmd);
}
sh. exit();

Appendix: Introduction to shell commands

The following information about shell commands comes from AndroidStudio User Guide: Shell Commandsopen in new window.

am command

The am command is the Activity Manager command, which is used to manage application activities, services, etc.

The following commands start with "am", for example shell('am start -p com.tencent.mm');(start WeChat)

start [options] intent

Start the Activity (application activity) specified by the intent. See Specifications for intent parameters.

Options include:

  • -D: Enable debugging.
  • -W: Wait for boot to complete.
  • --start-profiler file: Start profiler and send results to file.
  • -P file: Like --start-profiler, but profiling stops when the app goes idle.
  • -R count: Repeat Activity start count times. Before each repetition, the top Activity will complete.
  • -S: Forcibly stop the target application before starting the Activity.
  • --opengl-trace: Enable tracing of OpenGL functions.
  • --user user_id | current: Specifies which user to run as; if not specified, runs as the current user.

startservice [options] intent

Start the Service specified by the intent. See Specifications for intent parameters. Options include:

  • --user user_id | current: Specifies which user to run as; if not specified, runs as the current user.

force-stop package

Force stop all applications associated with package ([app package name](#app package name)).

kill [options] package

Terminate all processes associated with package ([application package name](#application package name)). This command only terminates processes that are safe to terminate without affecting the user experience. Options include:

  • --user user_id | all | current: Specifies the user whose processes will be terminated; if not specified, all users' processes will be terminated.

kill-all

Kill all background processes.

broadcast [options] intent

Issue a broadcast intent. See Specifications for intent parameters.

Options include:

  • [--user user_id | all | current]: Specify the user to send to; if not specified, send to all users.

instrument [options] component

Start monitoring with an Instrumentation instance. Typically, the target component is of the form test_package/runner_class. Options include:

  • -r: output raw result (otherwise decode report_key_streamresult). Use with [-e perf true] to generate raw output of performance measurements.
  • -e name value: set the parameter name to value. For test runners, the general form is -e testrunner_flag value[,value...].
  • -p file: write profiling data to file.
  • -w: Wait for instrumentation to complete before returning. Test runners are required to use this option.
  • --no-window-animation: Turn off window animation at runtime.
  • --user user_id | current: Specifies which user the instrument runs in; if not specified, it runs in the current user.
  • profile start process file Start the profiler of process, write the result to file.
  • profile stop process Stops the profiler for a process.

dumpheap [options] process file

Dump the heap of the process, writing to file.

Options include:

  • --user [user_id|current]: When providing a process name, specify the process user to dump; if not specified, use the current user.
  • -n: Dump native heap instead of managed heap.
  • set-debug-app [options] package Set application package to debug.

Options include:

  • -w: Wait for the debugger when the application starts.
  • --persistent: Persist this value.
  • clear-debug-app Use set-debug-app to clear packages previously set for debugging purposes.

monitor [options] Enable monitoring for crashes or ANRs.

Options include:

  • --gdb: start gdbserv on the given port on crash/ANR.

screen-compat {on|off} package

Controls the screen compatibility mode of the package.

display-size [reset|widthxheight]

Replace emulator/device display size. This command is useful for testing your app on screens of different sizes, allowing a device with a large screen to emulate a small screen resolution (and vice versa). Example:

shell("am display-size 1280x800", true);

display-density dpi

Replace emulator/device display density. This command is useful for testing your app on screens of different densities, enabling testing on high-density ambient environments with low-density screens (and vice versa). Example:

shell("am display-density 480", true);

to-uri intent

Output the given intent specification as a URI. See Specifications for intent parameters.

to-intent-uri intent

Output the given intent specification as intent:URI. See the specification for the intent parameter.

specification of intent parameters

For am commands that take an intent parameter, you can specify the intent with the following options:

  • -a action Specifies the intent action, such as "android.intent.action.VIEW". This designation can only be declared once.
  • -d data_uri Specify an intent data URI, such as "content://contacts/people/1". This designation can only be declared once.
  • -t mime_type Specify the intent MIME type, such as "image/png". This designation can only be declared once.
  • -c category Specify an intent category, such as "android.intent.category.APP_CONTACTS".
  • -n component Specify the component name prefixed with the package name to create an explicit intent, such as "com.example.app/.ExampleActivity".
  • -f flags Add flags to intents supported by setFlags().
  • --esn extra_key Add a null extra. URI intent does not support this option.
  • -e|--es extra_key extra_string_value Add string data as key-value pairs.
  • --ez extra_key extra_boolean_value Add boolean data as key-value pairs.
  • --ei extra_key extra_int_value Add integer data as key-value pairs.
  • --el extra_key extra_long_value Add long integer data as key-value pairs.
  • --ef extra_key extra_float_value Add float data as key-value pairs.
  • --eu extra_key extra_uri_value Add URI data as key-value pairs.
  • --ecn extra_key extra_component_name_value Add the component name, convert and pass it as a ComponentName object.
  • --eia extra_key extra_int_value[,extra_int_value...] Add an array of integers.
  • --ela extra_key extra_long_value[,extra_long_value...] Add an array of long integers.
  • --efa extra_key extra_float_value[,extra_float_value...] Add an array of floats.
  • --grant-read-uri-permission Contains the flag FLAG_GRANT_READ_URI_PERMISSION.
  • --grant-write-uri-permission Contains the flag FLAG_GRANT_WRITE_URI_PERMISSION.
  • --debug-log-resolution Contains the flag FLAG_DEBUG_LOG_RESOLUTION.
  • --exclude-stopped-packages Include the flag FLAG_EXCLUDE_STOPPED_PACKAGES.
  • --include-stopped-packages Include flag FLAG_INCLUDE_STOPPED_PACKAGES.
  • --activity-brought-to-front Contains the flag FLAG_ACTIVITY_BROUGHT_TO_FRONT.
  • --activity-clear-top Contains the flag FLAG_ACTIVITY_CLEAR_TOP.
  • --activity-clear-when-task-reset Contains the flag FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET.
  • --activity-exclude-from-recents Include the flag FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS.
  • --activity-launched-from-history Contains the flag FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY.
  • --activity-multiple-task Contains the flag FLAG_ACTIVITY_MULTIPLE_TASK.
  • --activity-no-animation Contains the flag FLAG_ACTIVITY_NO_ANIMATION.
  • --activity-no-history Contains the flag FLAG_ACTIVITY_NO_HISTORY.
  • --activity-no-user-action Contains the flag FLAG_ACTIVITY_NO_USER_ACTION.
  • --activity-previous-is-top Contains the flag FLAG_ACTIVITY_PREVIOUS_IS_TOP.
  • --activity-reorder-to-front Contains the flag FLAG_ACTIVITY_REORDER_TO_FRONT.
  • --activity-reset-task-if-needed Contains the flag FLAG_ACTIVITY_RESET_TASK_IF_NEEDED.
  • --activity-single-top Contains the flag FLAG_ACTIVITY_SINGLE_TOP.
  • --activity-clear-task Contains the flag FLAG_ACTIVITY_CLEAR_TASK.
  • --activity-task-on-home Contains the flag FLAG_ACTIVITY_TASK_ON_HOME.
  • --receiver-registered-only Contains the flag FLAG_RECEIVER_REGISTERED_ONLY.
  • --receiver-replace-pending Contains the flag FLAG_RECEIVER_REPLACE_PENDING.
  • --selector The -d and -t options are required to set the intent data and type.

URI component package

If you are not restricted by one of the options above, you can specify the URI, package name, and component name directly. When the parameter is unrestricted, if the parameter contains a ":" (colon), the tool assumes that the parameter is a URI; if the parameter contains a "/" (forward slash), the tool assumes that the parameter is a component name; Otherwise, the tool assumes the argument is a package name.

Application package name

The so-called application package name is an identifier that uniquely determines the application. For example, the package name of WeChat is "com.tencent.mm", and the package name of QQ is "com.tencent.mobileqq". To get the package name of an application, it can be obtained through the function getPackageName(appName). See Help -> Other general functions.

pm command

The pm command is used to manage applications, such as uninstalling applications, freezing applications, etc. The following commands all start with "pm", such as "shell("pm disable com.tencent.mm");" (freeze WeChat)

list packages [options] filter

Print all packages, or, alternatively, only packages whose package names contain the text in filter. options:

  • -f: View their associated files.
  • -d: Filter to show only deprecated packages.
  • -e: Filter to show only enabled packages.
  • -s: Filter to show only system packages.
  • -3: Filter to show only third-party packages.
  • -i: View the installer of the package.
  • -u: Also include uninstalled packages.
  • --user user_id: The user space to query.

list permission-groups

Print all known permission groups.

list permissions [options] group

Print all known permissions, or, only those in group. options:

  • -g: Organize by groups.
  • -f: output all information.
  • -s: short summary.
  • -d: list only dangerous permissions.
  • -u: List only the permissions the user will see.

list instrumentation [options]

List all test packages. options:

  • -f: List APK files for testing packages.
  • target_package: List the test packages only for this app.

list features

All functions of the output system.

list libraries

Output all libraries supported by the current device.

list users

Print all users on the system.

path package

Outputs the path to the APK for the given package.

install [options] path

Install the package (specified by path) to the system. options:

  • -l: Install packages with forward locking.
  • -r: Reinstall an existing application, preserving its data.
  • -t: Allow installation of test APKs.
  • -i installer_package_name: Specifies the installer package name.
  • -s: Install packages on shared mass storage (like sdcard).
  • -f: Install packages on internal system memory.
  • -d: allow version code downgrade.
  • -g: Grant all permissions listed in the application manifest file.

uninstall [options] package

Uninstalls a package from the system. options:

  • -k: Keep data and cache directories after removing packages.

clear package

Deletes all data associated with the package.

enable package_or_component

Enable the given package or component (written as "package/class").

disable package_or_component

Deactivate a given package or component (written as "package/class").

disable-user [options] package_or_component

options:

  • --user user_id: The user to deactivate.

grant package_name permission

Grant permissions to the app. On devices running Android 6.0 (API level 23) and higher, this can be any permission declared in the app's manifest. Required to be an optional app-defined permission on devices running Android 5.1 (API level 22) and lower.

revoke package_name permission

Revoke permissions from the app. On devices running Android 6.0 (API level 23) and higher, this can be any permission declared in the app's manifest. Required to be an optional app-defined permission on devices running Android 5.1 (API level 22) and lower.

set-install-location location

Change the default install location. Position value:

  • 0: Auto - Let the system decide the best position. *1: Internal—Installed on internal device storage. *2: External—installed on external media.

NOTE: This command is for debugging purposes only; using this command can cause application breaks and other unexpected behavior.

get-install-location

Returns the current install location. return value:

  • 0 [auto]: Let the system decide the best position.
  • 1 [internal]: Install on internal device storage
  • 2 [external]: Install on external media

set-permission-enforced permission [true|false]

Specifies whether the given permission should be enforced.

trim-caches desired_free_space

Reduce cache files to reach the given free space.

create-user user_name

Create a new user with the given user_name, outputting the new user's identifier.

remove-user user_id

Remove the user with the given user_id, deleting all data associated with that user.

get-max-users

The maximum number of users supported by the output device.

Other commands

Take a screenshot

The screencap command is a shell utility for taking screenshots of a device's display. In the shell, this syntax is:

screencap filename

E.g:

$ shell("screencap /sdcard/screen.png");

list file

ls filepath

E.g:

log(shell("ls /system/bin").result);
Last update:
Contributors: Bruce