Android runs bash command in application

Hi, I am developing an application that requires me to run some bash code, is there a way that I can hardcode the script in my application and then run it? For example (this is a VERY simplified example)

#!/system/bin/sh # if [ ! -f /sdcard/hello.txt ] then echo 'Hello World' >> /sdcard/hello.txt else echo 'Goodbye World' >> /sdcard/goodbye.txt fi 

I have the following method to run a single line of bash commands, but you need to run something like the one on multiple lines. Again, the above code is a very simplified example of what I'm actually doing, should be executed through a script and cannot be executed through java. I also want it to be hardcoded, I know that a script can be saved on the phone and run it with the following, but I do not want the script to be hardcoded in the application just there.

 public Boolean execCommand(String command) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.flush(); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (IOException e) { return false; } catch (InterruptedException e) { return false; } return true; } 

Thanks for the help in my problem.

+6
source share
1 answer

If you understand correctly, all you have to do is change the one-line example method to one that receives and sends multiple lines, for example:

  public Boolean execCommands(String... command) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); for(int i = 0; i < command.length; i++) { os.writeBytes(command[i] + "\n"); os.flush(); } os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (IOException e) { return false; } catch (InterruptedException e) { return false; } return true; } 

So you can call your multi-line bash commands like this:

  String[] commands = { "echo 'test' >> /sdcard/test1.txt", "echo 'test2' >>/sdcard/test1.txt" }; execCommands(commands); String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> /sdcard/foo.txt"; execCommands(commandText.split("\n")); 
+8
source

Source: https://habr.com/ru/post/898002/


All Articles