From c40246c9da5c6d46ece1c11a9f6cbc15c4068157 Mon Sep 17 00:00:00 2001 From: Gregory Chamberlain Date: Sat, 26 Sep 2020 04:14:56 +0100 Subject: [PATCH] Add section for testing file descriptor 1 --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 1fd0155..2b2664c 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ See something incorrectly described, buggy or outright wrong? Open an issue or s * [Get the current working directory](#get-the-current-working-directory) * [Get the PID of the current shell](#get-the-pid-of-the-current-shell) * [Get the current shell options](#get-the-current-shell-options) + * [Check if output is to a terminal](#check-if-output-is-to-a-terminal) * [AFTERWORD](#afterword) @@ -1003,6 +1004,29 @@ This is an alternative to the `pwd` built-in. "$-" ``` +## Check if output is to a terminal + +You can test whether file descriptor 1 (i.e. standard output) is open +on a terminal using `[ -t 1 ]`. This test fails if output is +redirected to a file (`>file`) or a pipe (`|cmd`). + +```shell +if [ -t 1 ]; then + echo terminal +else + echo not a terminal +fi +``` + +**Example usage:** + +```shell +# show output in color when called interactively +[ -t 1 ] && printf '\033[38;5;1m' +echo hey +[ -t 1 ] && printf '\033[m' +``` + # AFTERWORD Thanks for reading! If this bible helped you in any way and you'd like to give back, consider donating. Donations give me the time to make this the best resource possible. Can't donate? That's OK, star the repo and share it with your friends!