linjunshi
linjunshi

Reputation: 87

Can we run simple shell script in android system using react native?

I am writing a simple app using react native to make some file operations done automatically. I have tried packages like strong text react-native-fs, but I found that there are some files/folders that can not be read using

RNFS.ls(PATH). 

Trying to list files in that folder will throw an exception.

However, these files can be displayed using ls command in adb shell. So I am wondering if there is a way that we can run shell commands in react native like we make some system calls in java/python?

Thanks

Upvotes: 5

Views: 2550

Answers (2)

Li Zheng
Li Zheng

Reputation: 731

@flyskywhy/react-native-android-shell works well even with root command e.g.

AndroidShell.executeCommand('su -c ifconfig eth0 down; su -c ifconfig eth0 hw ether 19:21:19:49:20:21; su -c ifconfig eth0 up', (result) => {
  console.log(result)
});

Upvotes: 0

Joshua Pinter
Joshua Pinter

Reputation: 47581

Write your own Native Module.

You can easily run a shell command from Java and call it from React Native using React Native's Native Modules. You can find more information here:

https://facebook.github.io/react-native/docs/0.60/native-modules-android#callbacks

And for your Java command, you'd want to use something like this:

String command = "ls " + path; // Where path is your desired path.

Runtime runtime = Runtime.getRuntime();

Process result = runtime.exec( command );

BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( result.getInputStream() ) );

String[] parts = bufferedReader.readLine().split( "\\s+" );

Upvotes: 2

Related Questions