简体   繁体   中英

How do I determine if my bash terminal window is maximized?

I have a bash script that maximizes the terminal ( echo -ne '\\e[9;1t' ) on start-up and resets it ( echo -ne '\\e[9;0t' ) at shut-down which sucks when the script is launched from a terminal that is already maximized. I want to detect if the terminal is already maximized, and if so skip the maximize/reset portion of the script, but I can't find where I can detect if the terminal is maximized in bash. How can I do that?

The same set of escape sequences (see Window manipulation (from dtterm, as well as extensions) has

Ps = 1 1  -> Report xterm window state.  If the xterm window
 is open (non-iconified), it returns CSI 1 t .  If the xterm
  window is iconified, it returns CSI 2 t .

Your "\\e[" is "CSI" in this context. Using bash's "read -t" for example, you can read the response.

From the comments, I'm reminded that the question is for maximized , and suggested that codes 18 and 19 could be used. However, due to window decorations (title/border) there is no way that the result from 18 would match that from 19. In discussion, a problem was noted with bash's "read -t" - which I see was not a good recommendation (it appears that bash modifies the stty modes). Here is an example which would read the given responses, without attempting to use "read -t":

#!/bin/bash

get_reply() {
    TTY=$(tty)
    exec </dev/tty
    OLD=$(stty -g)
    stty raw -echo min 0 time 5 2>/dev/null
    printf '\033[%st' "$*" >/dev/tty
    read reply
    stty $OLD 2>/dev/null
    exec < $TTY

    content=$(echo ".$reply" | sed -e 's/^.[//' -e 's/t$//')
    echo "REPLY:$content"
    echo "$reply" |od -bc
}

get_size() {
    get_reply "$1"
    content=$(echo ".$content" | sed -e "s/^.$2;//")
    echo "...$content"
}

if printf '\033]0;%s\007' "Testing" >/dev/tty
then
    get_reply 11
    if [ $content = 1 ]
    then
            get_size 18 8
            get_size 19 9
    else
            echo "** iconified"
    fi
else
    echo "? not a tty" >&2
    exit 1
fi

Because a solution would have to simply read the original size and save it (somewhere), there are simpler ways to read the size. For example, the stty and resize programs provide the information more easily:

$ stty -a |head -n 1
speed 38400 baud; rows 40; columns 80; line = 0;

and

$ resize -u
COLUMNS=80;
LINES=40;
export COLUMNS LINES;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM