You did not get an Exception, because the ls
command is not Java and communicates not with exceptions but with error messages on STDERR
and exit codes.
Actually you must understand what the shell does when you enter a command and what the command does. Therefore a shell command line like this
ls -1s --block-size=1 20130328094916142/received/is*.* $dir| awk '{print $2"\t"$1}'
is handled by the shell this way:
- shell: expand that
20130328094916142/received/is*.*
into a list of filenames
- shell: expand the
$dir
part into a list of filenames
- shell: execute the
ls
command with the arguments
ls
-1s
--block-size=1
- each expanded filename as a separate argument
- shell: execute
awk
command with the argument
- shell: connect the output of
ls
to the input of awk
- ls: evaluate arguments
- awk: read each line, process it with the given script and output the result.
You see: the expansion of environment variables and wildcards is done by the shell, not by ls
.
Back to Java:
execute
does NOT process the arguments like a shell. That is up to you. Therefore your call is the shell equivalent roughly like this:
ls '-1s' '--block-size=1' '20130328094916142/received/is*.*' '$dir' '|' 'awk' '{print $2"\t"$1}'
everything is quoted, even the pipe, hence nothing is expanded by the shell.
So far the problem. What are the solutions?
- You can emulate the shell and do the expansion in Java. Have fun with this. (I.e. this is not a real solution).
- You can call a shell from Java instead of
ls
.
The later is like this:
a shell has usually a -c
option where you can give it one command string which is then evaluated in the same way as a real typed command line.
So you call the command like this
String[] args = {
"/bin/sh",
"-c",
"ls -1s --block-size=1 20130328094916142/received/is*.* $dir| awk '{print $2\"\t\"$1}'"
};
Process process3 = Runtime.getRuntime().exec(args);
Although the correct quoting of the awk
command might need some more work.