Android在app中运行bash命令

嗨,我正在开发一个应用程序,它要求我运行一些bash代码是否有一种方法,我可以硬编码脚本到我的应用程序,然后运行它? 例如(这是一个非常简化的例子)

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

我有以下方法来运行一行bash命令,但需要运行类似于多行的东西。 再说上面的代码是一个非常简单的例子,我实际上在做什么必须通过脚本运行,不能通过java完成。 我也想让它硬编码我知道可以将脚本存储在手机上并使用以下内容运行它但不希望脚本只是在那里它宁愿它在应用程序中硬编码。

 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; } 

感谢您对我的问题的任何帮助

如果我理解正确,你所要做的就是将一行示例方法更改为接受并发送多行的内容,如下所示:

  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; } 

这样,您可以像这样调用多行bash命令:

  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"));