6

This runs as expected in an xterm: sha512sum <filename> | cut -c -$COLUMNS, but not within a #! /bin/bash script such as dothis.sh <args>, because $COLUMNS is not known, so to say.

I'd rather not pass $COLUMNS as an argument, nor export it to the environment.

The script is not critical, needs to run only on one machine, on a commandline in an xterm.

Linux pre 3.2.0-4-amd64 #1 SMP Debian 3.2.81-2 x86_64 GNU/Linux
GNU bash, version 4.2.37
XTerm(278)
4
COLUMNS=$(tput cols)

Or in one line

sha512sum <filename> | cut -c -"$(tput cols)"
  • 1
    Or eval $( resize) – DarkHeart Oct 18 '16 at 23:10
  • As the earliest, almost immediate answer, marking this one as accepted, noting that for my situation, it is spot-on, cut-to-the-chase. – Randy Oct 19 '16 at 16:45
8

bash sets shell variables COLUMNS and LINES in interactive mode (there have been issues with its checkwinsize feature which led to this distinction). You could get that information in different ways.

From the context of the question, you know how to make a shell script, but are uncertain where to get useful data.

In my window, I have 40 rows, 80 columns:

  • tput cols tries the environment variables first (since they're not set in your environment, that's just as well), then tries the system's terminal settings, and then the terminal descriptions. Putting the size in the terminal description is not done much anymore; it's a crutch used by termcap applications (such as bash). You would get just a single number, e.g.,

    40

    Owing to a historical glitch, on a FreeBSD system (see history and portability notes), you would have to use tput co, because (although ncurses with terminfo is used as the system library), ncurses' tput is not used with FreeBSD. NetBSD and OpenBSD, of course, went off into other tangents.

  • stty size (available on many platforms) gives the lines/columns values from the terminal settings - or nothing if those are not available. It gives just two numbers, which can be split easily in a shell:

    40 80

  • resize tries the terminal itself (using escape sequences) and updates the terminal settings to match. For bash, you would use resize -u, giving output like this:

    COLUMNS=80;
    LINES=40;
    export COLUMNS LINES;

None of those choices is much use in cron because there is no terminal involved. But they are all usable in a terminal.

  • Thanks for the through reply. I'm using tput since it works good enough and outputs the single number. – Randy Oct 19 '16 at 16:42
  • ooops, "thorough" – Randy Oct 19 '16 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.