端末サイズ取得サンプルスクリプト(bash)

Format
Shell
Post date
2017-08-09 10:15
Publication Period
Unlimited
  1. #!/bin/bash
  2. die() {
  3. echo "$@"
  4. exit 1
  5. }
  6. printf "\e[18t"
  7. read -r -t 1 -n 3 resp
  8. [ $? -ne 0 ] && die "No response"
  9. CSI=$(printf "\x9b")
  10. ESC=$(printf "\e")
  11. case $resp in
  12. ${CSI}8\;) : ;;
  13. ${ESC}\[8)
  14. read -r -t 1 -n 1 resp
  15. [ $? -ne 0 -o "$resp" != ";" ] && die "Invalid Response";;
  16. *) echo "Invalid response";;
  17. esac
  18. state=0
  19. cols=0
  20. rows=0
  21. while [ $state -lt 3 ]; do
  22. read -r -t 1 -n 1 resp
  23. [ $? -ne 0 ] && die "Invalid Response"
  24. case $resp in
  25. [0-9])
  26. if [ $state -eq 0 ]; then
  27. rows=$((rows * 10 + resp))
  28. elif [ $state -eq 1 ]; then
  29. cols=$((cols * 10 + resp))
  30. fi;;
  31. \;) [ $state -lt 2 ] && state=$((++state));;
  32. t) state=3;;
  33. *) die "Invalid response";;
  34. esac
  35. done
  36. echo "COLUMNS=$cols"
  37. echo "ROWS=$rows"
Download Printable view

URL of this paste

Embed with JavaScript

Embed with iframe

Raw text