Add examples/is_tty.clj (#812) [skip ci]

This commit is contained in:
Thiago Kenji Okada 2021-04-29 11:39:13 -03:00 committed by GitHub
parent e26f26c1ba
commit a8247c9762
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View file

@ -31,6 +31,7 @@
- [fzf](#fzf) - [fzf](#fzf)
- [digitalocean-ping.clj](#digitalocean-pingclj) - [digitalocean-ping.clj](#digitalocean-pingclj)
- [download-aliases.clj](#download-aliasesclj) - [download-aliases.clj](#download-aliasesclj)
- [Is TTY?](#is-tty)
Here's a gallery of useful examples. Do you have a useful example? PR welcome! Here's a gallery of useful examples. Do you have a useful example? PR welcome!
@ -431,3 +432,33 @@ $ bb digitalocean-ping.clj
## [download-aliases.clj](download-aliases.clj) ## [download-aliases.clj](download-aliases.clj)
Download deps for all aliases in a deps.edn project. Download deps for all aliases in a deps.edn project.
## [Is TTY?](is_tty.clj)
An equivalent of Python's `os.isatty()` in Babashka, to check if the
`stdin`/`stdout`/`stderr` is connected to a TTY or not (useful to check if the
script output is being redirect to `/dev/null`, for example).
Only works in Unix systems.
``` shell
$ bb is-tty.clj
STDIN is TTY?: true
STDOUT is TTY?: true
STDERR is TTY?: true
$ bb is-tty.clj </dev/null
STDIN is TTY?: false
STDOUT is TTY?: true
STDERR is TTY?: true
$ bb is-tty.clj 1>&2 >/dev/null
STDIN is TTY?: true
STDOUT is TTY?: false
STDERR is TTY?: true
$ bb is-tty.clj 2>/dev/null
STDIN is TTY?: true
STDOUT is TTY?: true
STDERR is TTY?: false
```

21
examples/is_tty.clj Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env bb
(ns is-tty
(:require [babashka.process :as p]))
(defn- is-tty
[fd key]
(-> ["test" "-t" (str fd)]
(p/process {key :inherit :env {}})
deref
:exit
(= 0)))
(defn in-is-tty? [] (is-tty 0 :in))
(defn out-is-tty? [] (is-tty 1 :out))
(defn err-is-tty? [] (is-tty 2 :err))
(when (= *file* (System/getProperty "babashka.file"))
(println "STDIN is TTY?:" (in-is-tty?))
(println "STDOUT is TTY?:" (out-is-tty?))
(println "STDERR is TTY?:" (err-is-tty?)))