Architucas
Architucas

Reputation: 129

cant run simple bash command in linux, permission denied

I'm trying to run a simple command from console using this

public void execute(File file, String... command){

    Process p = null;
    ProcessBuilder builder = new ProcessBuilder("ls");
    builder.directory(file.getAbsoluteFile());
    builder.redirectErrorStream(true);

    try {
        p = builder.start();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

but it kept saying that I cant run ls, permission denied. Is there any missing step here?

Thanks

Upvotes: 3

Views: 1155

Answers (3)

erip
erip

Reputation: 16935

You should use pass the commands and the flags to the constructor of the ProcessBuilder separately (as per the docs):

public void execute(File file, String... command) {

    ProcessBuilder builder = new ProcessBuilder("ls", "-l");
    builder.directory(file.getAbsoluteFile());
    builder.redirectErrorStream(true);

    try {
        Process p = builder.start();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

It seems you want to execute command, though. To do this, you can pass command to ProcessBuilder's constructor.

public void execute(File file, String... command) {

    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(file.getAbsoluteFile());
    builder.redirectErrorStream(true);

    try {
        Process p = builder.start();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

Here's the ideone to the working code

You'll notice that when I run it with "ls -l", there's a problem executing the command. This is because the first argument is treated as the command to be executed and the remaining arguments are treated as flags.


To change permissions of bash commands in EC2 instances, execute

chmod u+x /home/admin/ec2-api-tools-*/bin/*

Upvotes: 1

Eugene K
Eugene K

Reputation: 3457

ProcessBuilder builder = new ProcessBuilder("ls -l");

There is no process named "ls -l". You want to use the process named "ls" with the arguments "-l", for that you need:

ProcessBuilder builder = new ProcessBuilder("ls", "-l");

Upvotes: 1

Jake Psimos
Jake Psimos

Reputation: 640

This depends on a couple of things: 1) The user that runs java (your process will be ran as that user) 2) The directory where your JAR or class resides.

Also make sure that your account has proper permissions if the java user is not the same as the user you are logged in as.

Upvotes: 1

Related Questions