pure-bash-bible/manuscript/chapter15.txt

80 lines
1.3 KiB
Plaintext
Raw Normal View History

# Information about the terminal
## Get the terminal size in lines and columns (*from a script*)
This is handy when writing scripts in pure bash and `stty`/`tput` cant be
called.
**Example Function:**
```sh
get_term_size() {
# Usage: get_term_size
# (:;:) is a micro sleep to ensure the variables are
# exported immediately.
shopt -s checkwinsize; (:;:)
printf '%s\n' "$LINES $COLUMNS"
}
```
**Example Usage:**
```shell
# Output: LINES COLUMNS
$ get_term_size
15 55
```
## Get the terminal size in pixels
**CAVEAT**: This does not work in some terminal emulators.
**Example Function:**
```sh
get_window_size() {
# Usage: get_window_size
printf '%b' "${TMUX:+\\ePtmux;\\e}\\e[14t${TMUX:+\\e\\\\}"
IFS=';t' read -d t -t 0.05 -sra term_size
printf '%s\n' "${term_size[1]}x${term_size[2]}"
}
```
**Example Usage:**
```shell
# Output: WIDTHxHEIGHT
$ get_window_size
1200x800
# Output (fail):
$ get_window_size
x
```
## Get the current cursor position
This is useful when creating a TUI in pure bash.
**Example Function:**
```sh
get_cursor_pos() {
# Usage: get_cursor_pos
IFS='[;' read -p $'\e[6n' -d R -rs _ y x _
printf '%s\n' "$x $y"
}
```
**Example Usage:**
```shell
# Output: X Y
$ get_cursor_pos
1 8
```
<!-- CHAPTER END -->