shell - Shell commands
Shell refers to the Unix shell: a set of commands used to interact with the operating system on Unix-like systems.
Many programs can execute shell commands, such as terminal emulators.
In Auto.js, this roughly corresponds to running adb shell. Internally there are two execution approaches:
- Execute via
java.lang.Runtime.exec(e.g.shell,Tap,Home, etc.) - Execute via the embedded terminal emulator (e.g.
RootAutomator,Shellobjects)
Stability: 2 - Stable
shell(cmd[, root])
cmd{string} Command to executeroot{Boolean} Whether to run with root privileges. Defaultfalse.
Executes cmd once and returns the execution result. The returned object has:
code{number} Exit code. 0 for success, non-zero for failure.result{string} Stdout outputerror{string} Stderr output. For example, running a root-only command without root may return"Permission denied".
Example (force stop WeChat):
var result = shell("am force-stop com.tencent.mm", true);
log(result);
console.show();
if (result.code == 0) {
toast("Success");
} else {
toast("Failed. Check the console for details.");
}shell(cmd, options)
cmd{string} Command to executeoptions{Object} Options:root{boolean} Whether to run with root privileges. Defaultfalse.adb{boolean} Whether to execute via adb. Defaultfalse.
Executes cmd once and returns the result. The returned object shape is the same as shell(cmd[, root]).
// Execute via adb
var result = shell("pm list packages", { adb: true });
log(result.result);$shell.checkAccess(permission)
permission{string} Permission type:"root"Check root access"adb"Check adb access
- Returns {boolean} Whether the permission is available
Checks whether the current environment has the specified permission.
if ($shell.checkAccess("root")) {
log("Has root access");
} else {
log("No root access");
}
if ($shell.checkAccess("adb")) {
log("Has adb access");
} else {
log("No adb access");
}$shell.isRootAvailable()
- Returns {boolean} Whether root is available
Checks whether root is available on the device. Even if it returns true, it does not mean the current script has root permission—it only means the device supports root.
if ($shell.isRootAvailable()) {
log("Device supports root");
// Try to get root permission
var result = shell("su -c 'id'", true);
if (result.code == 0) {
log("Root granted");
} else {
log("Failed to obtain root");
}
} else {
log("Device does not support root");
}$shell.setDefaultOptions(options)
options{Object} Default options:root{boolean} Use root by defaultadb{boolean} Execute via adb by default
Sets default options for the shell function. After setting, calling shell(cmd) uses these defaults.
// Default to root
$shell.setDefaultOptions({ root: true });
// After that, shell(cmd) uses root by default
var result = shell("pm list packages");
log(result.result);
// If you don't want root, pass it explicitly
var result2 = shell("pm list packages", false);Shell
Stability: 2 - Stable
The shell() function is designed for executing a single command once and getting its result. If you need to execute multiple commands, using a Shell object is more efficient: each shell() call starts a new shell process and closes it after finishing (which takes time), while a Shell object reuses the same shell process throughout its lifetime.
new Shell(root)
root{Boolean} Whether to run the shell process with root. Defaultfalse. This affects the permissions of commands executed by thisShellinstance.
Constructor for Shell.
var sh = new Shell(true);
// Force stop WeChat
sh.exec("am force-stop com.tencent.mm");
sh.exit();Shell.exec(cmd)
cmd{string} Command to execute
Executes cmd. This function returns nothing.
Note: command execution is asynchronous and non-blocking. It does not wait for completion before continuing.
This design can be inconvenient, but due to limitations of the embedded terminal emulator there is currently no better option. If a solution becomes available in the future, Shell.execAndWaitFor may be provided.
Shell.exit()
Exits the shell immediately. Any running command will be terminated.
Shell.exitAndWaitFor()
Executes the "exit" command and waits until the exit finishes and the shell is closed.
This exits the shell gracefully by executing exit.
Shell.setCallback(callback)
callback{Object} Callback object
Sets callbacks for listening to shell output. It can include:
- onOutput {Function} Called whenever the shell outputs something. Argument is a string.
- onNewLine {Function} Called whenever a new line is produced. Argument is a string (without trailing newline).
Example:
var sh = new Shell();
sh.setCallback({
onNewLine: function (line) {
// Print each new line to console
log(line);
},
});
while (true) {
// Loop to read commands
var cmd = dialogs.rawInput("Enter a command (type exit to quit)");
if (cmd == "exit") {
break;
}
// Execute command
sh.exec(cmd);
}
sh.exit();Appendix: Shell command overview
The following shell command notes are adapted from Android Studio guide: Shell commands.
am command
am is the Activity Manager command, used for managing app activities, services, etc.
All commands below start with "am ". For example: shell("am start -p com.tencent.mm"); (start WeChat)
start [options] intent
Starts the Activity specified by the intent.
See Intent specification.
Options:
- -D: Enable debugging.
- -W: Wait for launch to complete.
- --start-profiler file: Start profiling and send results to
file. - -P file: Similar to --start-profiler, but stops profiling when the app goes idle.
- -R count: Repeat Activity launch
counttimes. Before each repeat, finish the top Activity. - -S: Force stop the target app before starting the Activity.
- --opengl-trace: Enable OpenGL function tracing.
- --user user_id | current: Run as the specified user, or current if omitted.
startservice [options] intent
Starts the Service specified by the intent.
See Intent specification.
Options:
- --user user_id | current: Run as the specified user, or current if omitted.
force-stop package
Force stop all apps associated with the given package name.
kill [options] package
Kill all processes associated with the given package. This only kills processes that are safe to stop and should not affect user experience.
Options:
- --user user_id | all | current: Which user's processes to kill. If omitted, kills for all users.
kill-all
Kill all background processes.
broadcast [options] intent
Send a broadcast intent. See Intent specification.
Options:
- [--user user_id | all | current]: Send to the specified user, or all users if omitted.
instrument [options] component
Start monitoring using an Instrumentation instance. Typically the target component is in the form test_package/runner_class.
Options:
- -r: Output raw results (otherwise decodes report_key_streamresult). Combine with
-e perf truefor raw performance output. - -e name value: Set an argument. For test runners:
-e testrunner_flag value[,value...]. - -p file: Write profiling data to
file. - -w: Wait for instrumentation to finish before returning (required for test runners).
- --no-window-animation: Disable window animations while running.
- --user user_id | current: Run instrumentation as the specified user (defaults to current).
- profile start process file: Start profiling
processand write results tofile. - profile stop process: Stop profiling
process.
dumpheap [options] process file
Dump the heap of process to file.
Options:
- --user [user_id|current]: Which user to dump (defaults to current).
- -n: Dump native heap instead of managed heap.
- set-debug-app [options] package: Set the package to debug.
Options:
- -w: Wait for debugger on app start.
- --persistent: Persist this value.
- clear-debug-app: Clear previously set debug app.
monitor [options] Monitor crashes or ANRs.
Options:
- --gdb: Start gdbserv on the given port when a crash/ANR occurs.
screen-compat {on|off} package
Control the screen-compatibility mode for a package.
display-size [reset|widthxheight]
Override emulator/device display size. Useful for testing on different screen sizes; you can emulate a smaller resolution on a large-screen device (and vice versa).
Example:
shell("am display-size 1280x800", true);display-density dpi
Override emulator/device display density. Useful for testing on different densities; you can test low-density behavior on a high-density environment (and vice versa).
Example:
shell("am display-density 480", true);to-uri intent
Print the given intent spec as a URI. See Intent specification.
to-intent-uri intent
Print the given intent spec as an intent:URI. See Intent specification.
Intent specification
For am commands that take an intent, you can specify the intent using these options:
- -a action
Specify the intent action, e.g."android.intent.action.VIEW". Can be declared only once. - -d data_uri
Specify the intent data URI, e.g."content://contacts/people/1". Can be declared only once. - -t mime_type
Specify the intent MIME type, e.g."image/png". Can be declared only once. - -c category
Specify an intent category, e.g."android.intent.category.APP_CONTACTS". - -n component
Specify a component name with package prefix to create an explicit intent, e.g."com.example.app/.ExampleActivity". - -f flags
Add flags supported bysetFlags(). - --esn extra_key
Add a null extra. URI intents do not support this option. - -e|--es extra_key extra_string_value
Add a string extra (key-value pair). - --ez extra_key extra_boolean_value
Add a boolean extra (key-value pair). - --ei extra_key extra_int_value
Add an integer extra (key-value pair). - --el extra_key extra_long_value
Add a long extra (key-value pair). - --ef extra_key extra_float_value
Add a float extra (key-value pair). - --eu extra_key extra_uri_value
Add a URI extra (key-value pair). - --ecn extra_key extra_component_name_value
Add a component name extra (converted and passed as aComponentNameobject). - --eia extra_key extra_int_value[,extra_int_value...]
Add an integer array extra. - --ela extra_key extra_long_value[,extra_long_value...]
Add a long array extra. - --efa extra_key extra_float_value[,extra_float_value...]
Add a float array extra. - --grant-read-uri-permission
Include flagFLAG_GRANT_READ_URI_PERMISSION. - --grant-write-uri-permission
Include flagFLAG_GRANT_WRITE_URI_PERMISSION. - --debug-log-resolution
Include flagFLAG_DEBUG_LOG_RESOLUTION. - --exclude-stopped-packages
Include flagFLAG_EXCLUDE_STOPPED_PACKAGES. - --include-stopped-packages
Include flagFLAG_INCLUDE_STOPPED_PACKAGES. - --activity-brought-to-front
Include flagFLAG_ACTIVITY_BROUGHT_TO_FRONT. - --activity-clear-top
Include flagFLAG_ACTIVITY_CLEAR_TOP. - --activity-clear-when-task-reset
Include flagFLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET. - --activity-exclude-from-recents
Include flagFLAG_ACTIVITY_EXCLUDE_FROM_RECENTS. - --activity-launched-from-history
Include flagFLAG_ACTIVITY_LAUNCHED_FROM_HISTORY. - --activity-multiple-task
Include flagFLAG_ACTIVITY_MULTIPLE_TASK. - --activity-no-animation
Include flagFLAG_ACTIVITY_NO_ANIMATION. - --activity-no-history
Include flagFLAG_ACTIVITY_NO_HISTORY. - --activity-no-user-action
Include flagFLAG_ACTIVITY_NO_USER_ACTION. - --activity-previous-is-top
Include flagFLAG_ACTIVITY_PREVIOUS_IS_TOP. - --activity-reorder-to-front
Include flagFLAG_ACTIVITY_REORDER_TO_FRONT. - --activity-reset-task-if-needed
Include flagFLAG_ACTIVITY_RESET_TASK_IF_NEEDED. - --activity-single-top
Include flagFLAG_ACTIVITY_SINGLE_TOP. - --activity-clear-task
Include flagFLAG_ACTIVITY_CLEAR_TASK. - --activity-task-on-home
Include flagFLAG_ACTIVITY_TASK_ON_HOME. - --receiver-registered-only
Include flagFLAG_RECEIVER_REGISTERED_ONLY. - --receiver-replace-pending
Include flagFLAG_RECEIVER_REPLACE_PENDING. - --selector
Requires-dand-toptions to set intent data and type.
URI component package
If not restricted by one of the options above, you can directly specify a URI, package name, or component name. When not restricted: if the argument contains a : (colon), it is treated as a URI; if it contains a / (slash), it is treated as a component name; otherwise it is treated as a package name.
Package name
An app package name uniquely identifies an Android app. For example, WeChat is "com.tencent.mm" and QQ is "com.tencent.mobileqq".
To get an app's package name, you can call getPackageName(appName).
pm command
pm is the package manager command, used for managing apps (uninstall, disable, etc.).
All commands below start with "pm ". For example: shell("pm disable com.tencent.mm"); (disable WeChat)
list packages [options] filter
Print all packages, or only packages whose name contains the given filter text.
Options:
- -f: See the associated APK file.
- -d: Only show disabled packages.
- -e: Only show enabled packages.
- -s: Only show system packages.
- -3: Only show third-party packages.
- -i: Show package installer.
- -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 permissions in the given group.
Options:
- -g: Organize by group.
- -f: Print all information.
- -s: Short summary.
- -d: Only list dangerous permissions.
- -u: Only list permissions shown to users.
list instrumentation [options]
List all instrumentation (test) packages.
Options:
- -f: List the APK file for each test package.
- target_package: Only list test packages targeting this app.
list features
Print all features of the system.
list libraries
Print all libraries supported by the current device.
list users
Print all users on the system.
path package
Print the APK path for the given package.
install [options] path
Install a package (specified by path) to the system.
Options:
- -l: Install the package with forward lock.
- -r: Reinstall an existing app, keeping its data.
- -t: Allow test APKs to be installed.
- -i installer_package_name: Specify the installer package name.
- -s: Install on shared mass storage (e.g. sdcard).
- -f: Install on internal system memory.
- -d: Allow version code downgrade.
- -g: Grant all runtime permissions listed in the app manifest.
uninstall [options] package
Uninstall a package from the system.
Options:
- -k: Keep data and cache directories after removal.
clear package
Delete all data associated with the package.
enable package_or_component
Enable the given package or component (written as "package/class").
disable package_or_component
Disable the given package or component (written as "package/class").
disable-user [options] package_or_component
Options:
- --user user_id: The user to disable for.
grant package_name permission
Grant a permission to an app. On Android 6.0+ (API 23+), it can be any permission declared in the app manifest. On Android 5.1 and below (API 22-), it must be an optional permission defined by the app.
revoke package_name permission
Revoke a permission from an app. On Android 6.0+ (API 23+), it can be any permission declared in the app manifest. On Android 5.1 and below (API 22-), it must be an optional permission defined by the app.
set-install-location location
Change the default install location. Values:
- 0: auto — let the system decide best location.
- 1: internal — install on internal device storage.
- 2: external — install on external media.
Note: this command is for debugging only; it may cause app breakage and other unexpected behavior.
get-install-location
Return the current install location. Values:
- 0 [auto]: Let the system decide best location.
- 1 [internal]: Install on internal device storage.
- 2 [external]: Install on external media.
set-permission-enforced permission [true|false]
Specify whether the given permission should be enforced.
trim-caches desired_free_space
Trim cache files to reach the desired free space.
create-user user_name
Create a new user with the given user_name, and print 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
Print the maximum number of users supported by the device.
Other commands
Take a screenshot
The screencap command is a shell utility for taking a screenshot of the device display. In the shell, the syntax is:
screencap filenameExample:
$ shell("screencap /sdcard/screen.png");List files
ls filepathExample:
log(shell("ls /system/bin").result);