pure-bash-bible/manuscript/chapter17.txt

80 lines
1.3 KiB
Plaintext
Raw Normal View History

2018-06-23 02:34:15 +02:00
# INFORMATION ABOUT THE TERMINAL
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
## 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.
2018-06-20 05:03:53 +02:00
**Example Function:**
```sh
2018-06-23 02:34:15 +02:00
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"
2018-06-20 05:03:53 +02:00
}
```
**Example Usage:**
```shell
2018-06-23 02:34:15 +02:00
# Output: LINES COLUMNS
$ get_term_size
15 55
2018-06-20 05:03:53 +02:00
```
2018-06-23 02:34:15 +02:00
## Get the terminal size in pixels
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
**CAVEAT**: This does not work in some terminal emulators.
2018-06-20 05:03:53 +02:00
**Example Function:**
```sh
2018-06-23 02:34:15 +02:00
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]}"
2018-06-20 05:03:53 +02:00
}
```
**Example Usage:**
```shell
2018-06-23 02:34:15 +02:00
# Output: WIDTHxHEIGHT
$ get_window_size
1200x800
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
# Output (fail):
$ get_window_size
x
2018-06-20 05:03:53 +02:00
```
2018-06-23 02:34:15 +02:00
## Get the current cursor position
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
This is useful when creating a TUI in pure bash.
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
**Example Function:**
2018-06-20 05:03:53 +02:00
2018-06-23 02:34:15 +02:00
```sh
get_cursor_pos() {
# Usage: get_cursor_pos
IFS='[;' read -p $'\e[6n' -d R -rs _ y x _
printf '%s\n' "$x $y"
2018-06-20 05:03:53 +02:00
}
```
2018-06-23 02:34:15 +02:00
**Example Usage:**
2018-06-20 05:03:53 +02:00
```shell
2018-06-23 02:34:15 +02:00
# Output: X Y
$ get_cursor_pos
1 8
2018-06-20 05:03:53 +02:00
```
<!-- CHAPTER END -->