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 usevalue=$(</home/test/Documents/terminal.txt)#Get tty using the PID from terminal.txtTERMINAL=$(ps h -p $value -o tty)echo $TERMINAL#Use tty to get full filepath for terminal in useTERMINALPATH=/dev/$TERMINALecho $TERMINALPATHCOLUMNS=$(/home/test/Documents/get_columns.sh)echo $COLUMNSget_columns.sh#!/usr/bin/env bashecho $(/usr/bin/tput cols)The normal output of TERMINAL & TERMINALPATH are pts/terminalnumber and /dev/pts/terminalnumber, for example pts/0 & /dev/pts/0
Getting console width using a bash script
shell script;terminal;tput
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/1columns=$(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.