diff --git a/examples/README.md b/examples/README.md index 9eb0c0d1..7211218c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -31,6 +31,7 @@ - [fzf](#fzf) - [digitalocean-ping.clj](#digitalocean-pingclj) - [download-aliases.clj](#download-aliasesclj) + - [Is TTY?](#is-tty) 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 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 &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 +``` diff --git a/examples/is_tty.clj b/examples/is_tty.clj new file mode 100755 index 00000000..ac797ff7 --- /dev/null +++ b/examples/is_tty.clj @@ -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?)))