0

I'm currently trying to get the number of columns the terminal has in Java. For that I know there is an environment variable $COLUMNS, so I try to run 'echo $COLUMNS' and read its output, but for some weird reason I get a value that makes no sense, and on top of that, I always get the same value, no matter how I resize the terminal.

This is my code:

public static final String[] COLS = {"/bin/sh", "-c", "echo $COLUMNS </dev/tty"};

    public int getColumns(){
    try{
        Process p = Runtime.getRuntime().exec(CONST.COLS);
        p.waitFor();
        InputStreamReader in = new InputStreamReader(p.getInputStream());
        int cols = in.read();
        return cols;
    }catch(Exception e){
        System.out.println(e);
    }
    return 0;
    }
  • You're redirecting STDIN into your 'echo' command from /dev/tty, which isn't going to work. What happens if you just type `echo $COLUMNS` at the command line? – rojomoke Nov 20 '13 at 18:00
  • It prints the number of columns. What do I have to do then? Tried without the – user3014149 Nov 20 '13 at 20:47
  • I'm afraid I don't know Java, so I'm not sure I can really help any more. However, $COLUMNS is a feature in Bash, not the Bourne shell, so try changing /bin/sh to /bin/bash (or whatever the path on your system is). – rojomoke Nov 22 '13 at 07:11

1 Answers1

1

Try to run the tput command instead.

To get number of columns:

tput cols

The man page for tput.

benjamin.d
  • 2,801
  • 3
  • 23
  • 35
  • Same problem, now gives me another value, but still not the correct one and still a constant one. – user3014149 Nov 20 '13 at 20:47
  • 1
    Using tput directly won't work. I always get 80. The solution is to use redirection magic. See http://stackoverflow.com/questions/1286461/can-i-find-the-console-width-with-java/18883172#18883172 – malaverdiere Apr 16 '14 at 14:30