简体   繁体   中英

Java Runtime.exec() doesn't honor Linux alias

I have a compiled third party java program which uses Runtime.exec() to spawn a process but i wanted to add additional arguments to the process when the process starts using alias, but Java Runtime.exec() doesn't seem to honor. I tried with my own program but still it doesn't see to work , any help ?

import java.io.*;
        public class Exec {
          public static void main(String args[]) {
            try {
              String line;
              Process p = Runtime.getRuntime().exec(args[0]);
              BufferedReader bri = new BufferedReader
                (new InputStreamReader(p.getInputStream()));
              BufferedReader bre = new BufferedReader
                (new InputStreamReader(p.getErrorStream()));
              while ((line = bri.readLine()) != null) {
                System.out.println(line);
              }
              bri.close();
              while ((line = bre.readLine()) != null) {
                System.out.println(line);
              }
              bre.close();
              p.waitFor();
              System.out.println("Done.");
            }
            catch (Exception err) {
              err.printStackTrace();
            }
          }
        }

Output:

alias ls='ls -ltr'

java Exec ls 
Exec.class
Exec.java


ls 
-rw-r--r--    1 user  staff        1216 May 16 09:40 Exec.class
-rw-r--r--    1 user  staff         710 May 16 09:41 Exec.java

The reason is that alias is belonged to interactive shell process, so that the java can't see it.

You can see the detail here https://unix.stackexchange.com/questions/1496/why-doesnt-my-bash-script-recognize-aliases

If you want to execute the alias:

Your shell is bash java Exec "bash -i -c 'ls'"

Your shell is zsh java Exec "zsh -i -c 'ls'"

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