Printing my Mac's serial number in java using Unix commands
Question: I am trying to print my mac's [edit: Apple computer] serial number in a java
program. I am familiar with the Unix command

    
    
    ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'
    

which accomplishes this task in terminal.  
When I try

    
    
    String command = "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4; }'"
    Runtime terminal = Runtime.getRuntime(); 
    String input = new BufferedReader(
        new InputStreamReader(
            terminal.exec(commands).getInputStream())).readLine();
    System.out.println(new BufferedReader(
        new InputStreamReader(
            terminal.exec(command, args).getInputStream())).readLine());
    

my serial number is not printed. Instead it prints:

    
    
    <+-o Root class IORegistryEntry, id 0x100000100, retain 10>  
    

I think the problem is that `terminal.exec()` is not meant to take the whole
command string. Is there something in java similar to the argument `shell =
True` in python's `Popen(command, stdout=PIPE, shell=True)` that will allow me
to pass the whole command string?


Answer: I see two possibilities:

  1. Parse the output of `ioreg -l` using, say, [Scanner](http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html).

  2. Wrap the command in a shell script and `exec()` it:

    
    
    #!/bin/sh
    ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'
    

Addendum: As an example of using
[`ProcessBuilder`](http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html),
and incorporating a helpful suggestion by [Paul
Cager](http://stackoverflow.com/users/683825/paul-cager), here's a third
alternative:

    
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class PBTest {
    
        public static void main(String[] args) {
            ProcessBuilder pb = new ProcessBuilder("bash", "-c",
                "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'");
            pb.redirectErrorStream(true);
            try {
                Process p = pb.start();
                String s;
                // read from the process's combined stdout & stderr
                BufferedReader stdout = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
                while ((s = stdout.readLine()) != null) {
                    System.out.println(s);
                }
                System.out.println("Exit value: " + p.waitFor());
                p.getInputStream().close();
                p.getOutputStream().close();
                p.getErrorStream().close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    

