Felipe
Felipe

Reputation: 7583

Execute ls star with Runtime.getRuntime() on Linux

I wanto to execute Runtime.getRuntime().exec(); on Java to list files on some directory.

So I wanto to pass this command "ls /mnt/drbd7/i* | tail -1", but because the star the command returns null. And I realy need this star. I need to select the last file modified on the directory. I tryed to use java.io.File but it cannot get the last file.

Does anybody have a hint? Thanks in advance! Felipe

Upvotes: 0

Views: 1520

Answers (4)

Andreas Mayer
Andreas Mayer

Reputation: 695

Under Unix, patterns like * and ? in command line parameters are expanded by the command shells and not by the individual programs. There are some exceptions of programs that know how to handle wildcards, but ls is not one of them. The same goes for pipes: shells know how to handle them, java.lang.Runtime doesn't.

So, if you want to use these features, you would have to do something like this:

Runtime.getRuntime().exec("/bin/sh -c 'ls /mnt/drbd7/i* | tail -1'")

But note, that this is a very system-specific solution (it even depends on the current user's configuration) to a problem that can be solved with the means of pure Java (see java.io.File.listFiles, java.nio.file.DirectoryStream, etc).

Upvotes: 0

eskaev
eskaev

Reputation: 1128

The command ls /mnt/drbd7/i* | tail -1 won't display the last modified file, since the command ls sorts the results by name, by default. You can do ls -t /mnt/drbd7/i* | head -1 instead.

You could use the answer to this question:

How do I find the last modified file in a directory in Java?

Upvotes: 1

Reimeus
Reimeus

Reputation: 159844

You need to pass the command through the bash shell to that it can do a glob to convert the wildcards to a file list:

Runtime.getRuntime().exec(new String[]{ "/bin/bash", "-c", "ls", "/mnt/drbd7/i*", "|", "tail", "-1"});

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200206

You need to pass the command to a shell which will expand the star—and interpret the pipe symbol. You are starting not one, but two processes.

bash -c ls /mnt/drbd7/i* | tail -1

Upvotes: 1

Related Questions