blob: 135ce853524389f6cbc63c9e886071f66002e50a [file] [log] [blame]
Denis Vlasenko9a3b7b12007-08-03 08:48:44 +00001/* vi: set sw=4 ts=4: */
Denis Vlasenkoc01af952007-08-02 22:23:47 +00002/*
3 * Replacement for "stty size", which is awkward for shell script use.
4 * - Allows to request width, height, or both, in any order.
Denis Vlasenko9a3b7b12007-08-03 08:48:44 +00005 * - Does not complain on error, but returns width 80, height 24.
Denis Vlasenkoc01af952007-08-02 22:23:47 +00006 * - Size: less than 200 bytes
Denis Vlasenko9a3b7b12007-08-03 08:48:44 +00007 *
8 * Copyright (C) 2007 by Denys Vlasenko <vda.linux@googlemail.com>
9 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020010 * Licensed under GPLv2, see file LICENSE in this source tree.
Denis Vlasenkoc01af952007-08-02 22:23:47 +000011 */
Denys Vlasenkofb4da162016-11-22 23:14:24 +010012//config:config TTYSIZE
13//config: bool "ttysize"
14//config: default y
15//config: help
16//config: A replacement for "stty size". Unlike stty, can report only width,
17//config: only height, or both, in any order. It also does not complain on
18//config: error, but returns default 80x24.
19//config: Usage in shell scripts: width=`ttysize w`.
Pere Orga5bc8c002011-04-11 03:29:49 +020020
Denys Vlasenkof88e3bf2016-11-22 23:54:17 +010021//applet:IF_TTYSIZE(APPLET(ttysize, BB_DIR_USR_BIN, BB_SUID_DROP))
22
23//kbuild:lib-$(CONFIG_TTYSIZE) += ttysize.o
24
Pere Orga5bc8c002011-04-11 03:29:49 +020025//usage:#define ttysize_trivial_usage
26//usage: "[w] [h]"
27//usage:#define ttysize_full_usage "\n\n"
28//usage: "Print dimension(s) of stdin's terminal, on error return 80x25"
29
Denis Vlasenkoc01af952007-08-02 22:23:47 +000030#include "libbb.h"
31
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000032int ttysize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko2ec91ae2010-01-04 14:15:38 +010033int ttysize_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoc01af952007-08-02 22:23:47 +000034{
Denis Vlasenkob44c7902008-03-17 09:29:43 +000035 unsigned w, h;
Denis Vlasenkoc01af952007-08-02 22:23:47 +000036 struct winsize wsz;
Denis Vlasenko319f8eb2007-08-13 11:09:30 +000037
Denis Vlasenkoc01af952007-08-02 22:23:47 +000038 w = 80;
39 h = 24;
40 if (!ioctl(0, TIOCGWINSZ, &wsz)) {
41 w = wsz.ws_col;
42 h = wsz.ws_row;
43 }
44
Denys Vlasenko2ec91ae2010-01-04 14:15:38 +010045 if (!argv[1]) {
Denis Vlasenkoc01af952007-08-02 22:23:47 +000046 printf("%u %u", w, h);
47 } else {
48 const char *fmt, *arg;
49
50 fmt = "%u %u" + 3; /* "%u" */
51 while ((arg = *++argv) != NULL) {
52 char c = arg[0];
53 if (c == 'w')
54 printf(fmt, w);
55 if (c == 'h')
56 printf(fmt, h);
57 fmt = "%u %u" + 2; /* " %u" */
58 }
59 }
Denis Vlasenko4daad902007-09-27 10:20:47 +000060 bb_putchar('\n');
Denis Vlasenkoc01af952007-08-02 22:23:47 +000061 return 0;
62}