Add examples/is_tty.clj (#812) [skip ci]
This commit is contained in:
parent
e26f26c1ba
commit
a8247c9762
2 changed files with 52 additions and 0 deletions
|
|
@ -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
21
examples/is_tty.clj
Executable 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?)))
|
||||||
Loading…
Reference in a new issue