• Stars
    star
    710
  • Rank 63,751 (Top 2 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Execute shell commands on Android or the JVM

KtSh

An open source library to execute shell commands on Android or the JVM, written in Kotlin.

License Build Status Maven Central

Downloads

Download the latest JAR or grab via Gradle:

implementation 'com.jaredrummler:ktsh:1.0.0'

Alternatively, you can simply copy Shell.kt file to your project.

Usage

Basic usage:

val shell = Shell("sh")                         // create a shell
val result = shell.run("echo 'Hello, World!'")  // execute a command
if (result.isSuccess) {                         // check if the exit-code was 0
    println(result.stdout())                    // prints "Hello, World!"
}

Construct a new Shell instance:

// Construct a new shell instance with additional environment variables
val shell = Shell("sh", "USER" to "Chuck Norris", "ENV_VAR" to "VALUE")

// Construct a new shell instance with path to the shell:
val bash = Shell("/bin/bash")

Note: If the shell does not exist a Shell.NotFoundException is thrown as a RuntimeException.

Execute a command and get the result:

val shell = Shell.SH
val result: Shell.Command.Result = shell.run("ls")

A Shell.Command.Result contains the following:

  • stdout: A list of lines read from the standard input stream.
  • stderr: A list of lines read from the standard error stream.
  • exitCode: The exit status from running the command.
  • details: Additional information (start, stop, elapsed time, id, command)

Add a callback when stdout or stderr is read:

shell.addOnStderrLineListener(object : Shell.OnLineListener {
  override fun onLine(line: String) {
      // do something
  }
})

Add a callback that is invoked each time a command completes:

shell.addOnCommandResultListener(object : Shell.OnCommandResultListener {
  override fun onResult(result: Shell.Command.Result) {
    // do something with the result
  }
})

Execute a command with custom options:

Optionally, you can configure how each command executes by setting a timeout, redirecting stderr to stdout, add callbacks for when the command reads a line from stdout/stderr or is cancelled.

// NOTE: all of these are optional
val result = Shell.SH.run(command) {
  // Kill the command after 1 minute
  timeout = Shell.Timeout(1, TimeUnit.MINUTES)
  // Redirect STDOUT to STDERR
  redirectErrorStream = false
  // Callbacks:
  onCancelled = {
    // The command was cancelled
  }
  onStdErr = { line: String ->
    // Do something when reading a line from standard error stream
  }
  onStdOut = { line: String ->
    // Do something when reading a line from standard output stream
  }
  // Do not notify any listeners added via Shell.addOnStderrLineListener and Shell.addOnStdoutLineListener
  notify = false
}

Check the state of the shell:

if (shell.isRunning()) {
  // The shell is running a command
} else if (shell.isShutdown()) {
  // The shell has been killed
} else if (shell.isIdle()) {
  // The shell is open and not running any commands
}

or

when (shell.state) {
  State.Idle -> TODO()
  State.Running -> TODO()
  State.Shutdown -> TODO()
}

Shutdown the shell

shell.shutdown()

Interrupt waiting for a command to complete:

shell.interrupt()

Background processing on Android

Creating a new instance of a Shell or executing commands should be done on a separate thread other than the UI thread. This is up to the library user. An example of this can be found in the demo project using Kotlin coroutines and AndroidX libraries:

fun run(
    shell: Shell,
    command: String,
    callback: (result: Shell.Command.Result) -> Unit
) = viewModelScope.launch {
    val result = withContext(Dispatchers.IO) { shell.run(command) }
    withContext(Dispatchers.Main) { callback(result) }
}

Structure

  • buildSrc - contains dependencies, plugins, versions for Gradle build logic
  • build.gradle.kts - root gradle config file
  • settings.gradle.kts - root gradle settings file
  • library - the ktsh library
  • library/src/test - unit tests for the library
  • demo - Android demo project using ktsh
  • scripts - scripts to publish library to maven central
  • .github - any files for the github page

Similar projects:

License

Copyright (C) 2021 Jared Rummler

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

AnimatedSvgView

Animated SVG Drawing for Android
Java
1,975
star
2

AndroidProcesses

DEPRECATED
Java
1,804
star
3

Cyanea

A theme engine for Android
Kotlin
1,451
star
4

AndroidDeviceNames

A small Android library to get the market name of an Android device.
Java
1,385
star
5

MaterialSpinner

A spinner view for Android
Java
1,324
star
6

ColorPicker

A highly customizable color picker for Android
Java
792
star
7

APKParser

APK parser for Android
Java
637
star
8

HtmlDsl

Build valid HTML for Android TextView
Kotlin
540
star
9

AndroidAnimations

A bunch of fun animations for Android.
Java
74
star
10

vector2svg

Convert Android VectorDrawable XML resource file to SVG
Java
67
star
11

android-shell-scripts

Shell scripts for Android
Shell
43
star
12

TrueTypeParser

TrueType Font Parser for Android
Java
38
star
13

FastScroll-RecyclerView

ReyclerView with fast scrolling and scroll popups
Java
35
star
14

TwoDScrollView

Java
20
star
15

snet-decompiled

SafetyNet Decompiled
Java
16
star
16

GooglePlayScraper

Simple web scraper to get app information from Google Play
Java
11
star
17

sfntly

A Library for Using, Editing, and Creating SFNT-based Fonts
Java
9
star
18

bootanimation-scripts

Shell
7
star
19

Movies

Simple movie app for Android
Java
7
star
20

Baking

Java
6
star
21

EasterEggs

Collection of easter eggs you can put in your app.
Java
5
star
22

BlockingDialog

Show a dialog from a background thread and wait for a result.
Java
3
star
23

SO-41872033

http://stackoverflow.com/questions/41872033/how-to-change-theme-from-another-app-resource-in-android
Java
2
star
24

UnixPermission

Unix permission parser written in Kotlin
Kotlin
2
star
25

now-wallpapers

44 Google Now Wallpapers
Java
2
star
26

java-code-styles

IntelliJ IDEA code style settings for Java and Android projects.
Shell
2
star
27

SimpleMvp

Java
1
star
28

github

This repository contains assets used in GitHub repo README.md files by GitHub user @jaredrummler
1
star
29

jaredrummler

1
star