Getting console width using a bash scriptresizable serial console window?How to set Cols and Lines for a...

Lost property on Portuguese trains

Sum ergo cogito?

How to find out the average duration of the peer-review process for a given journal?

How much does Commander Data weigh?

Heyacrazy: No Diagonals

How long do you think advanced cybernetic implants would plausibly last?

Numbers Decrease while Letters Increase

Are the players on the same team as the DM?

Are there any elected officials in the U.S. who are not legislators, judges, or constitutional officers?

Why isn't "I've" a proper response?

Why is 1. d4 Nf6 2. c4 e6 3. Bg5 almost never played?

How do the Etherealness and Banishment spells interact?

What are some interesting features that are common cross-linguistically but don't exist in English?

How do I prevent other wifi networks from showing up on my computer?

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

Do they have Supervillain(s)?

Tex Quotes(UVa 272)

Uri tokenizer as a simple state machine

Two questions about typesetting a Roman missal

Architectural feasibility of a tiered circular stone keep

How do I get toddlers to stop asking for food every hour?

Why did Khan ask Admiral James T. Kirk about Project Genesis?

Asymmetric table

How do I make my image comply with the requirements of this photography competition?



Getting console width using a bash script


resizable serial console window?How to set Cols and Lines for a SubprocessUsing a variable inside a sequence of commands in bash to supplement an existing string - syntax error or flawed design?Is it possible to open a terminal with specified tty/ptyDetect how much of Unicode my terminal supports, even through screenWhy do the terminal attributes look different from outside the terminal?bash - get pid for a script using the script filenamexfce4-Terminal doesn't create a new pts session?Bold and Underline using echo with emailShell output from one command as input to otherredirect input from keypad/mouse to shell dialog curses gui






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







14















I'm encountering an issue where I am trying to get the size of a terminal by using scripts. Normally I would use the command tput cols inside the console, however I want to be able to accomplish this feature by strictly using scripts.



As of now I am able to detect the running console and get its file path. However I'm struggling to use this information to get the console's width. I've attempted using the command tput, but I'm fairly new to Linux/scripts so therefore don't really know what to do.



The reason for doing this is I want to be able to setup a cron entry that notifies the console of its width/columns every so often.



This is my code so far:



tty.sh



#!/bin/bash

#Get PID of terminal
#terminal.txt holds most recent PID of console in use
value=$(</home/test/Documents/terminal.txt)

#Get tty using the PID from terminal.txt
TERMINAL="$(ps h -p $value -o tty)"
echo $TERMINAL

#Use tty to get full filepath for terminal in use
TERMINALPATH=/dev/$TERMINAL
echo $TERMINALPATH

COLUMNS=$(/home/test/Documents/get_columns.sh)
echo $COLUMNS


get_columns.sh



#!/usr/bin/env bash
echo $(/usr/bin/tput cols)


The normal output of TERMINAL & TERMINALPATH are pts/terminalnumber and /dev/pts/terminalnumber, for example pts/0 & /dev/pts/0










share|improve this question






















  • 1





    unix.stackexchange.com/questions/16578/… might help you.

    – phk
    Jul 29 '16 at 11:54











  • @phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

    – roaima
    Jul 29 '16 at 13:17











  • I didn't think cron jobs had controlling terminals.

    – TMN
    Jul 29 '16 at 16:08


















14















I'm encountering an issue where I am trying to get the size of a terminal by using scripts. Normally I would use the command tput cols inside the console, however I want to be able to accomplish this feature by strictly using scripts.



As of now I am able to detect the running console and get its file path. However I'm struggling to use this information to get the console's width. I've attempted using the command tput, but I'm fairly new to Linux/scripts so therefore don't really know what to do.



The reason for doing this is I want to be able to setup a cron entry that notifies the console of its width/columns every so often.



This is my code so far:



tty.sh



#!/bin/bash

#Get PID of terminal
#terminal.txt holds most recent PID of console in use
value=$(</home/test/Documents/terminal.txt)

#Get tty using the PID from terminal.txt
TERMINAL="$(ps h -p $value -o tty)"
echo $TERMINAL

#Use tty to get full filepath for terminal in use
TERMINALPATH=/dev/$TERMINAL
echo $TERMINALPATH

COLUMNS=$(/home/test/Documents/get_columns.sh)
echo $COLUMNS


get_columns.sh



#!/usr/bin/env bash
echo $(/usr/bin/tput cols)


The normal output of TERMINAL & TERMINALPATH are pts/terminalnumber and /dev/pts/terminalnumber, for example pts/0 & /dev/pts/0










share|improve this question






















  • 1





    unix.stackexchange.com/questions/16578/… might help you.

    – phk
    Jul 29 '16 at 11:54











  • @phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

    – roaima
    Jul 29 '16 at 13:17











  • I didn't think cron jobs had controlling terminals.

    – TMN
    Jul 29 '16 at 16:08














14












14








14


3






I'm encountering an issue where I am trying to get the size of a terminal by using scripts. Normally I would use the command tput cols inside the console, however I want to be able to accomplish this feature by strictly using scripts.



As of now I am able to detect the running console and get its file path. However I'm struggling to use this information to get the console's width. I've attempted using the command tput, but I'm fairly new to Linux/scripts so therefore don't really know what to do.



The reason for doing this is I want to be able to setup a cron entry that notifies the console of its width/columns every so often.



This is my code so far:



tty.sh



#!/bin/bash

#Get PID of terminal
#terminal.txt holds most recent PID of console in use
value=$(</home/test/Documents/terminal.txt)

#Get tty using the PID from terminal.txt
TERMINAL="$(ps h -p $value -o tty)"
echo $TERMINAL

#Use tty to get full filepath for terminal in use
TERMINALPATH=/dev/$TERMINAL
echo $TERMINALPATH

COLUMNS=$(/home/test/Documents/get_columns.sh)
echo $COLUMNS


get_columns.sh



#!/usr/bin/env bash
echo $(/usr/bin/tput cols)


The normal output of TERMINAL & TERMINALPATH are pts/terminalnumber and /dev/pts/terminalnumber, for example pts/0 & /dev/pts/0










share|improve this question
















I'm encountering an issue where I am trying to get the size of a terminal by using scripts. Normally I would use the command tput cols inside the console, however I want to be able to accomplish this feature by strictly using scripts.



As of now I am able to detect the running console and get its file path. However I'm struggling to use this information to get the console's width. I've attempted using the command tput, but I'm fairly new to Linux/scripts so therefore don't really know what to do.



The reason for doing this is I want to be able to setup a cron entry that notifies the console of its width/columns every so often.



This is my code so far:



tty.sh



#!/bin/bash

#Get PID of terminal
#terminal.txt holds most recent PID of console in use
value=$(</home/test/Documents/terminal.txt)

#Get tty using the PID from terminal.txt
TERMINAL="$(ps h -p $value -o tty)"
echo $TERMINAL

#Use tty to get full filepath for terminal in use
TERMINALPATH=/dev/$TERMINAL
echo $TERMINALPATH

COLUMNS=$(/home/test/Documents/get_columns.sh)
echo $COLUMNS


get_columns.sh



#!/usr/bin/env bash
echo $(/usr/bin/tput cols)


The normal output of TERMINAL & TERMINALPATH are pts/terminalnumber and /dev/pts/terminalnumber, for example pts/0 & /dev/pts/0







shell-script terminal tput






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 29 '16 at 22:30









Gilles

571k138 gold badges1180 silver badges1692 bronze badges




571k138 gold badges1180 silver badges1692 bronze badges










asked Jul 29 '16 at 11:42









sirgeezer21sirgeezer21

731 silver badge7 bronze badges




731 silver badge7 bronze badges











  • 1





    unix.stackexchange.com/questions/16578/… might help you.

    – phk
    Jul 29 '16 at 11:54











  • @phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

    – roaima
    Jul 29 '16 at 13:17











  • I didn't think cron jobs had controlling terminals.

    – TMN
    Jul 29 '16 at 16:08














  • 1





    unix.stackexchange.com/questions/16578/… might help you.

    – phk
    Jul 29 '16 at 11:54











  • @phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

    – roaima
    Jul 29 '16 at 13:17











  • I didn't think cron jobs had controlling terminals.

    – TMN
    Jul 29 '16 at 16:08








1




1





unix.stackexchange.com/questions/16578/… might help you.

– phk
Jul 29 '16 at 11:54





unix.stackexchange.com/questions/16578/… might help you.

– phk
Jul 29 '16 at 11:54













@phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

– roaima
Jul 29 '16 at 13:17





@phk I don't think that helps. The issue there is how to tell the tty driver of actual values for columns/lines. Here it is to determine them from the tty driver.

– roaima
Jul 29 '16 at 13:17













I didn't think cron jobs had controlling terminals.

– TMN
Jul 29 '16 at 16:08





I didn't think cron jobs had controlling terminals.

– TMN
Jul 29 '16 at 16:08










4 Answers
4






active

oldest

votes


















17















The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.



The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.



Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:



terminal=/dev/pts/1
columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )d+')
rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )d+')




By the way, the construct echo $(/usr/bin/tput cols) is awful.



For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.






share|improve this answer




























  • Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

    – Stéphane Chazelas
    Jul 29 '16 at 13:44













  • @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

    – roaima
    Jul 29 '16 at 13:49








  • 1





    Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

    – Stéphane Chazelas
    Jul 29 '16 at 14:03











  • @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

    – roaima
    Jul 29 '16 at 15:13






  • 1





    I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

    – Random832
    Jul 30 '16 at 7:17





















13















tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.



So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:



{ cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"


(here open in read-only mode so tput doesn't output its error messages there).



Alternatively, you may be able to use stty size. stty queries the terminal on stdin:



read rows cols < <(stty size < "$TERMINALPATH")


None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.



The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.






share|improve this answer



































    7















    This script:



    #!/bin/bash

    echo "The number of columns are $COLUMNS"
    echo "The number of lines are $LINES"


    Worked here with absolutely nothing more.....



    Why you are setting a environment variable with data?
    COLUMNS=$(/home/test/Documents/get_columns.sh)



    Are you try to get the columns and lines from other script or tty? Is that it?
    Still strange for me because you're setting the columns environment variable for the local script....






    share|improve this answer




























    • This doesn't help retrieve the values within the OP's cron job for a particular terminal.

      – roaima
      Jul 29 '16 at 13:11













    • Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

      – Luciano Andress Martini
      Jul 29 '16 at 16:25













    • I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

      – roaima
      Jul 29 '16 at 16:27











    • @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

      – ingroxd
      Sep 15 '18 at 17:25











    • Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

      – Luciano Andress Martini
      Sep 16 '18 at 12:39



















    0















    My answer is different than that of Roaima's, since it is dynamic. His/Hers answer gives you the size of the terminal at creation. If you are for example using a tiling window manager, like i3 or bspwm, you would rather want to have the current width of the terminal. Thus I use ssty from the coreutils package:



    #!/bin/bash
    stty size | awk '{print $2}'


    Luciano's solution works flawless in xterm and xfce4-terminal. I dont know if all terminals set the $COLUMNS variable.






    share|improve this answer




























    • This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

      – roaima
      Dec 1 '18 at 7:58














    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f299067%2fgetting-console-width-using-a-bash-script%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    17















    The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.



    The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.



    Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:



    terminal=/dev/pts/1
    columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )d+')
    rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )d+')




    By the way, the construct echo $(/usr/bin/tput cols) is awful.



    For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.






    share|improve this answer




























    • Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

      – Stéphane Chazelas
      Jul 29 '16 at 13:44













    • @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

      – roaima
      Jul 29 '16 at 13:49








    • 1





      Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

      – Stéphane Chazelas
      Jul 29 '16 at 14:03











    • @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

      – roaima
      Jul 29 '16 at 15:13






    • 1





      I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

      – Random832
      Jul 30 '16 at 7:17


















    17















    The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.



    The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.



    Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:



    terminal=/dev/pts/1
    columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )d+')
    rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )d+')




    By the way, the construct echo $(/usr/bin/tput cols) is awful.



    For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.






    share|improve this answer




























    • Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

      – Stéphane Chazelas
      Jul 29 '16 at 13:44













    • @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

      – roaima
      Jul 29 '16 at 13:49








    • 1





      Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

      – Stéphane Chazelas
      Jul 29 '16 at 14:03











    • @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

      – roaima
      Jul 29 '16 at 15:13






    • 1





      I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

      – Random832
      Jul 30 '16 at 7:17
















    17














    17










    17









    The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.



    The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.



    Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:



    terminal=/dev/pts/1
    columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )d+')
    rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )d+')




    By the way, the construct echo $(/usr/bin/tput cols) is awful.



    For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.






    share|improve this answer















    The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.



    The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.



    Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:



    terminal=/dev/pts/1
    columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )d+')
    rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )d+')




    By the way, the construct echo $(/usr/bin/tput cols) is awful.



    For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 29 '16 at 13:18

























    answered Jul 29 '16 at 13:11









    roaimaroaima

    49.2k7 gold badges64 silver badges132 bronze badges




    49.2k7 gold badges64 silver badges132 bronze badges
















    • Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

      – Stéphane Chazelas
      Jul 29 '16 at 13:44













    • @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

      – roaima
      Jul 29 '16 at 13:49








    • 1





      Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

      – Stéphane Chazelas
      Jul 29 '16 at 14:03











    • @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

      – roaima
      Jul 29 '16 at 15:13






    • 1





      I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

      – Random832
      Jul 30 '16 at 7:17





















    • Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

      – Stéphane Chazelas
      Jul 29 '16 at 13:44













    • @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

      – roaima
      Jul 29 '16 at 13:49








    • 1





      Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

      – Stéphane Chazelas
      Jul 29 '16 at 14:03











    • @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

      – roaima
      Jul 29 '16 at 15:13






    • 1





      I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

      – Random832
      Jul 30 '16 at 7:17



















    Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

    – Stéphane Chazelas
    Jul 29 '16 at 13:44







    Which implementation/version of tput/nurses? Mine (ncurses 6.0.20160625) does the TIOCGWINSZ on stderr if it can't do it on stdout. cols=$(tput cols) or cols=$(tput cols 2<> /dev/ttyx) works just fine.

    – Stéphane Chazelas
    Jul 29 '16 at 13:44















    @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

    – roaima
    Jul 29 '16 at 13:49







    @StéphaneChazelas I've got 5.9+20140913-1+b1 originally installed from Debian "sid". Just looking for a newer version now.

    – roaima
    Jul 29 '16 at 13:49






    1




    1





    Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

    – Stéphane Chazelas
    Jul 29 '16 at 14:03





    Works as well with ncurses 5.7.20100313 here. Are you positive cols=$(tput cols 2<> /dev/tty1) doesn't work for you?

    – Stéphane Chazelas
    Jul 29 '16 at 14:03













    @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

    – roaima
    Jul 29 '16 at 15:13





    @StéphaneChazelas fascinating. You're right: if I move stdout away from a terminal, tput cols does read from stderr. I now need to work out how to rewrite my answer...

    – roaima
    Jul 29 '16 at 15:13




    1




    1





    I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

    – Random832
    Jul 30 '16 at 7:17







    I'd use stty size <"$terminal" | read rows columns instead of trying to parse stty -a

    – Random832
    Jul 30 '16 at 7:17















    13















    tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.



    So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:



    { cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"


    (here open in read-only mode so tput doesn't output its error messages there).



    Alternatively, you may be able to use stty size. stty queries the terminal on stdin:



    read rows cols < <(stty size < "$TERMINALPATH")


    None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.



    The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.






    share|improve this answer
































      13















      tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.



      So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:



      { cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"


      (here open in read-only mode so tput doesn't output its error messages there).



      Alternatively, you may be able to use stty size. stty queries the terminal on stdin:



      read rows cols < <(stty size < "$TERMINALPATH")


      None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.



      The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.






      share|improve this answer






























        13














        13










        13









        tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.



        So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:



        { cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"


        (here open in read-only mode so tput doesn't output its error messages there).



        Alternatively, you may be able to use stty size. stty queries the terminal on stdin:



        read rows cols < <(stty size < "$TERMINALPATH")


        None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.



        The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.






        share|improve this answer















        tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.



        So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:



        { cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"


        (here open in read-only mode so tput doesn't output its error messages there).



        Alternatively, you may be able to use stty size. stty queries the terminal on stdin:



        read rows cols < <(stty size < "$TERMINALPATH")


        None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.



        The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 29 '16 at 16:45

























        answered Jul 29 '16 at 14:19









        Stéphane ChazelasStéphane Chazelas

        331k58 gold badges646 silver badges1016 bronze badges




        331k58 gold badges646 silver badges1016 bronze badges


























            7















            This script:



            #!/bin/bash

            echo "The number of columns are $COLUMNS"
            echo "The number of lines are $LINES"


            Worked here with absolutely nothing more.....



            Why you are setting a environment variable with data?
            COLUMNS=$(/home/test/Documents/get_columns.sh)



            Are you try to get the columns and lines from other script or tty? Is that it?
            Still strange for me because you're setting the columns environment variable for the local script....






            share|improve this answer




























            • This doesn't help retrieve the values within the OP's cron job for a particular terminal.

              – roaima
              Jul 29 '16 at 13:11













            • Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

              – Luciano Andress Martini
              Jul 29 '16 at 16:25













            • I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

              – roaima
              Jul 29 '16 at 16:27











            • @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

              – ingroxd
              Sep 15 '18 at 17:25











            • Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

              – Luciano Andress Martini
              Sep 16 '18 at 12:39
















            7















            This script:



            #!/bin/bash

            echo "The number of columns are $COLUMNS"
            echo "The number of lines are $LINES"


            Worked here with absolutely nothing more.....



            Why you are setting a environment variable with data?
            COLUMNS=$(/home/test/Documents/get_columns.sh)



            Are you try to get the columns and lines from other script or tty? Is that it?
            Still strange for me because you're setting the columns environment variable for the local script....






            share|improve this answer




























            • This doesn't help retrieve the values within the OP's cron job for a particular terminal.

              – roaima
              Jul 29 '16 at 13:11













            • Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

              – Luciano Andress Martini
              Jul 29 '16 at 16:25













            • I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

              – roaima
              Jul 29 '16 at 16:27











            • @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

              – ingroxd
              Sep 15 '18 at 17:25











            • Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

              – Luciano Andress Martini
              Sep 16 '18 at 12:39














            7














            7










            7









            This script:



            #!/bin/bash

            echo "The number of columns are $COLUMNS"
            echo "The number of lines are $LINES"


            Worked here with absolutely nothing more.....



            Why you are setting a environment variable with data?
            COLUMNS=$(/home/test/Documents/get_columns.sh)



            Are you try to get the columns and lines from other script or tty? Is that it?
            Still strange for me because you're setting the columns environment variable for the local script....






            share|improve this answer















            This script:



            #!/bin/bash

            echo "The number of columns are $COLUMNS"
            echo "The number of lines are $LINES"


            Worked here with absolutely nothing more.....



            Why you are setting a environment variable with data?
            COLUMNS=$(/home/test/Documents/get_columns.sh)



            Are you try to get the columns and lines from other script or tty? Is that it?
            Still strange for me because you're setting the columns environment variable for the local script....







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 29 '16 at 16:28

























            answered Jul 29 '16 at 11:59









            Luciano Andress MartiniLuciano Andress Martini

            4,50413 silver badges40 bronze badges




            4,50413 silver badges40 bronze badges
















            • This doesn't help retrieve the values within the OP's cron job for a particular terminal.

              – roaima
              Jul 29 '16 at 13:11













            • Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

              – Luciano Andress Martini
              Jul 29 '16 at 16:25













            • I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

              – roaima
              Jul 29 '16 at 16:27











            • @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

              – ingroxd
              Sep 15 '18 at 17:25











            • Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

              – Luciano Andress Martini
              Sep 16 '18 at 12:39



















            • This doesn't help retrieve the values within the OP's cron job for a particular terminal.

              – roaima
              Jul 29 '16 at 13:11













            • Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

              – Luciano Andress Martini
              Jul 29 '16 at 16:25













            • I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

              – roaima
              Jul 29 '16 at 16:27











            • @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

              – ingroxd
              Sep 15 '18 at 17:25











            • Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

              – Luciano Andress Martini
              Sep 16 '18 at 12:39

















            This doesn't help retrieve the values within the OP's cron job for a particular terminal.

            – roaima
            Jul 29 '16 at 13:11







            This doesn't help retrieve the values within the OP's cron job for a particular terminal.

            – roaima
            Jul 29 '16 at 13:11















            Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

            – Luciano Andress Martini
            Jul 29 '16 at 16:25







            Ahn? What? Now i am more confused, how can cronjobs scripts can have width????? They actually not run in a terminal.

            – Luciano Andress Martini
            Jul 29 '16 at 16:25















            I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

            – roaima
            Jul 29 '16 at 16:27





            I know. The cron job queries a particular terminal for its characteristics. (I'm not entirely sure why it needs to do this, but that's what the OP wants.)

            – roaima
            Jul 29 '16 at 16:27













            @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

            – ingroxd
            Sep 15 '18 at 17:25





            @LucianoAndressMartini $COLUMNS and $LINES are bash variables, it does not work (for example) in dash and posh

            – ingroxd
            Sep 15 '18 at 17:25













            Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

            – Luciano Andress Martini
            Sep 16 '18 at 12:39





            Tks. I really know, but my script is hashbang with /bin/bash i think it is supposed for you to know that you should use it. If you are using some unix without bash, maybe my answer not for you.

            – Luciano Andress Martini
            Sep 16 '18 at 12:39











            0















            My answer is different than that of Roaima's, since it is dynamic. His/Hers answer gives you the size of the terminal at creation. If you are for example using a tiling window manager, like i3 or bspwm, you would rather want to have the current width of the terminal. Thus I use ssty from the coreutils package:



            #!/bin/bash
            stty size | awk '{print $2}'


            Luciano's solution works flawless in xterm and xfce4-terminal. I dont know if all terminals set the $COLUMNS variable.






            share|improve this answer




























            • This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

              – roaima
              Dec 1 '18 at 7:58
















            0















            My answer is different than that of Roaima's, since it is dynamic. His/Hers answer gives you the size of the terminal at creation. If you are for example using a tiling window manager, like i3 or bspwm, you would rather want to have the current width of the terminal. Thus I use ssty from the coreutils package:



            #!/bin/bash
            stty size | awk '{print $2}'


            Luciano's solution works flawless in xterm and xfce4-terminal. I dont know if all terminals set the $COLUMNS variable.






            share|improve this answer




























            • This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

              – roaima
              Dec 1 '18 at 7:58














            0














            0










            0









            My answer is different than that of Roaima's, since it is dynamic. His/Hers answer gives you the size of the terminal at creation. If you are for example using a tiling window manager, like i3 or bspwm, you would rather want to have the current width of the terminal. Thus I use ssty from the coreutils package:



            #!/bin/bash
            stty size | awk '{print $2}'


            Luciano's solution works flawless in xterm and xfce4-terminal. I dont know if all terminals set the $COLUMNS variable.






            share|improve this answer















            My answer is different than that of Roaima's, since it is dynamic. His/Hers answer gives you the size of the terminal at creation. If you are for example using a tiling window manager, like i3 or bspwm, you would rather want to have the current width of the terminal. Thus I use ssty from the coreutils package:



            #!/bin/bash
            stty size | awk '{print $2}'


            Luciano's solution works flawless in xterm and xfce4-terminal. I dont know if all terminals set the $COLUMNS variable.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 19 '18 at 13:01

























            answered Feb 19 '18 at 11:26









            SashaSasha

            1012 bronze badges




            1012 bronze badges
















            • This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

              – roaima
              Dec 1 '18 at 7:58



















            • This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

              – roaima
              Dec 1 '18 at 7:58

















            This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

            – roaima
            Dec 1 '18 at 7:58





            This is no more dynamic then my answer. Both give you the terminal size at the point you run the commands.

            – roaima
            Dec 1 '18 at 7:58


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f299067%2fgetting-console-width-using-a-bash-script%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...