Last active
June 21, 2025 14:32
-
-
Save turboBasic/1b3dfa6601580ae39a21c1ad572d3263 to your computer and use it in GitHub Desktop.
Forcefully read text from terminal even when in pipeline #zsh #shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh | |
## Save initial state | |
exec {saved_stdin}<&0 # save initial stdin | |
exec {saved_stdout}>&1 # save initial stdout | |
## Redirect initial stdin and stdout to terminal | |
exec 1>/dev/tty # redirect output to terminal | |
exec 0</dev/tty # redirect input to terminal | |
## Now read everything from terminal, pipeline is ignored | |
# print prompt on terminal | |
print -P -n "%F{yellow}Enter value: %f" 1>/dev/tty | |
read text_from_terminal | |
# output to original stdout | |
echo "From terminal --> $text_from_terminal" 1>&$saved_stdout | |
## Restore stdin and close duplicated stdin | |
exec 0<&$saved_stdin | |
exec {saved_stdin}<&- | |
## Now read everything from initial stdin, eg. from pipeline | |
# print prompt on terminal | |
print -P "%F{yellow}Now read from standard input...%f" 1>/dev/tty | |
read text_from_stdin | |
# output to original stdout | |
echo "From standard input --> $text_from_stdin" 1>&$saved_stdout | |
## Restore stdout and close duplicated stdout | |
exec 1>&$saved_stdout | |
exec {saved_stdout}>&- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment