且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在java程序的不同目录中运行Bash命令

更新时间:2023-10-26 13:15:04

只是为了清楚地说明为什么你不能这样做, cd 命令不是像ar ls 这样的程序DF cd 由shell直接解释(并且shell会更改自己的工作目录,但是对于程序 shell执行 fork + exec 以将程序作为新进程执行。

Just to clearly state the why you cannot do that, the cd command is not a program like ar ls or df. cd is directly interpreted by the shell (and the shell changes its own working directory what will be inherited but child commands), while for programs, the shell executes a fork + exec to execute the program as a new process.

当您使用 runtime.exex(),你启动一个新进程来执行一个程序(并且已经说过 cd 不是程序)。执行脚本(它们也不是程序)的常用解决方法是使用 bash -c命令。但它几乎不会用于你,因为你只会改变子进程的工作目录,而下一步 exec 仍然会有java程序的工作目录。

When you use runtime.exex(), you start an new process to execute a program (and as already said cd is not a program). A common workaround to execute scripts (they too are not programs), is to use bash -c command. But it would be almost not use for you, because you would change the working directory of the child process only, and next exec would still have the working directory of the java program.

使用 cd 命令实现此目的的唯一方法是更改​​shell中的工作目录,并拥有此shell执行命令。类似于:

The only way to achieve that using cd command would be to change working directory in a shell, and have this shell execute the command. Something like :

    String Command ="bash -c (cd /home/user/project; du -s )";   //Bash Command
    // create a process and execute 
    Process p = Runtime.getRuntime().exec(Command);

当然,正确的方法是更改​​ exec中的工作目录命令本身,避免启动中间shell:

But of course, the correct way it change working directory in exec command itself, avoiding to start an intermediary shell :

    String Command ="du -s";   //Bash Command
    // create a process and execute 
    Process p = Runtime.getRuntime().exec(Command, null, new File("/home/user/project");