6

I know tabs command can be used to set the tab width of the terminal, but how can I know current tab width of the terminal (assuming the tabs are equidistant)? I can't find related information in tabs manual, do I miss something?

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Nan Xiao
  • 1,387
  • 6
  • 18
  • 33

2 Answers2

2

One could use a tab-width.sh script like that:

#!/usr/bin/env bash

echo -ne 'a\tb'  &&
    echo -ne "\033[6n"            # ask the terminal for the position
read -rs -d\[ _                   # discard the first part of the response
read -rs -dR foo                  # store the position in bash variable 'foo'
foo=$(cut -d";" -f2 <<< "$foo")   # discard row number
printf "\r\e[0K%d\n" $((foo - 2)) # subtract 2 for 'a' and 'b'

Adapted from this answer on StackOverflow. Example:

$ tabs 10

$ ./tab-width.sh
10
$ tabs 20

$ ./tab-width.sh
20
$ tabs 3

$ ./tab-width.sh
3

Use carefully, the script has not been tested thoroughly. It seems to work well in most cases although the same value is returned for both 1 and 2:

$ tabs 1

$ ./tab-width.sh
2
$ tabs 2

$ ./tab-width.sh
2

but one should notice that output returned by echo -e 'a\tb' is also the same in both cases.

Arkadiusz Drabczyk
  • 25,049
  • 5
  • 53
  • 68
0

Edit: The following doesn't actually work as I thought it did. Thank you @4wk_ for point this out in the comments :)


I've been using

echo $'\t' | wc -L

# typical output:
8

for this purpose.

  • echo $'\t' = prints a single tab character
  • wc = the "word counter" program
  • -L = aka --max-line-length; the switch that tells wc to calculate the line length, with tabs properly expanded

I've found this method to be quite portable between different TTYs and shells. The only thing I would add to increase portability is simply change the echo to:

echo -e "\t"

but tomato-tomato really.

Pyr3z
  • 1
  • 1