简体   繁体   中英

Run shell script with Angular CLI commands from Java

I'm trying to run a shell script from Java (using Runtime.getRuntime().exec(cmd)). All commands in the script file seem to be running normally except the angular-cli (ng) commands.

My Java File:

System.out.println("Executing Script...");
final String[] cmd = new String[]{"/bin/bash", "test.sh"};
final Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
    System.out.println("Script output: " + s);
}
process.destroy();
System.out.println("Script Executed.");

test.sh:

#!/bin/bash
cd ~/ && 
ng new newAngularProject &&

Outout:

Executing Script...
Script Executed.

No errors are thrown. All other commands work but for some reason, I'm unable to run ng commands. Also, I've tested the file w/o running it from Java - When I run the same script directly on the console, it works perfectly and all commands (including ng commands) work neatly. I'm running on MacOS in case you wanted to know.

Also print the error stream. You will get the error message, if it is there.

    final BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    while ((s = errorReader.readLine()) != null) {
        System.out.println("error: " + s);
    }

Also you can try to use absolute path of ng in your test.sh eg /home/my/install/node-vxxx/ng, since the process spawn by java to run your command might not get the environment variable you set in your .bashrc /.bash_aliases

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM