The "Cannot read" error in Linux terminals typically occurs when a script attempts to read from standard input (stdin) while stdin is redirected from a file or pipe, leaving no interactive source for user data. To resolve this, you must explicitly redirect the input stream from a specific file descriptor, such as /dev/tty or file descriptor 0, ensuring the command can access the terminal device directly rather than the redirected stream.
Understanding Standard Input Redirection
In Unix-like systems, every process starts with three standard streams: standard input (stdin), standard output (stdout), and standard error (stderr). By default, stdin is connected to your keyboard via the terminal emulator. When you use redirection operators like < or pipes |, you are changing where stdin points.
For example, if you run a command like my_script.sh < input.txt, the shell redirects the contents of input.txt into the program's stdin. If my_script.sh then tries to prompt the user for more information using a function like read in Bash, it will attempt to read from the already-exhausted or non-interactive file stream. This results in an immediate end-of-file condition or a permission error, manifesting as "Cannot read" or similar failures. This behavior is intentional by design to prevent scripts from accidentally blocking on interactive prompts when running unattended.
Why Interactive Commands Fail in Pipes
Many developers encounter this issue when chaining commands or writing automation scripts that require human intervention. A common scenario involves using tools that expect interactive input, such as password managers, confirmation prompts, or debugging consoles. When these tools are part of a pipeline, their expectation of a TTY (Teletype) device is broken. The operating system does not automatically restore the original terminal connection because doing so would compromise security and predictability. Instead, the program receives an empty stream or a closed file handle, leading to the runtime error. To fix this, you need to decouple the program's input requirement from the redirected stream. This is achieved by opening a new file descriptor that points directly to the controlling terminal of the current session. This allows the program to bypass the redirection and communicate with the user as if it were running in a fresh, unredirected shell.Solving the Issue with /dev/tty
The most robust solution for Ubuntu 20.04 and other Debian-based systems is to redirect the input specifically from the terminal device file/dev/tty. This special file represents the terminal associated with the current process, regardless of where standard input is currently pointed.
You can modify your script or command line to include this explicit redirection. For instance, if you have a Bash script that uses the read builtin, you can force it to read from the terminal by appending < /dev/tty to the command or within the script logic.
# Example of forcing read from terminal in a bash script
read -p "Enter your name: " username < /dev/tty
echo "Hello $username"
If you are running a command directly from the shell and cannot modify the source code, you can wrap the command in a subshell or use a here-string that ignores the outer redirection for specific parts. However, modifying the script itself is the cleanest approach for long-term stability.
Using File Descriptor Manipulation
An alternative advanced technique involves saving the original file descriptor for standard input before redirection occurs. You can assign the originalstdin to another file descriptor, such as FD 3, and then restore it when needed.
exec 3<&0 # Save original stdin to FD 3
cat input.txt | my_command < /dev/fd/3
This method is particularly useful in complex pipelines where multiple commands interact. It ensures that even if the main stream is piped, the specific command requiring interaction can still access the keyboard input through FD 3.
Common Pitfalls and Debugging Steps
When troubleshooting this error, ensure that you are not inadvertently creating nested redirections that conflict. For example, trying to redirect bothstdin and stdout to files while also reading from /dev/tty can sometimes cause buffering issues depending on the terminal emulator used.
If you are using a remote session via SSH, note that /dev/tty refers to the SSH channel's pseudo-terminal. Ensure that your SSH client has PTY allocation enabled, which is usually the default. If you are running scripts via cron jobs, remember that cron environments often lack a controlling terminal entirely. In such cases, reading from /dev/tty will fail because no TTY exists. You must provide default values or configuration files instead of interactive prompts for automated tasks.
Another frequent mistake is assuming that all commands support the same redirection syntax. While Bash handles < /dev/tty gracefully, some compiled C programs might hardcode their input sources or check for TTY status using isatty(). If a program explicitly checks for a TTY and refuses to run without one, you may need to use tools like expect to automate the interaction programmatically rather than relying on manual input.
For users experiencing console instability after crashes, refer to guides on restoring invisible console windows. Additionally, understanding terminal keystrokes can help in manually recovering sessions that appear frozen due to input errors.
How to Get Back Invisible Console/Bash Window After KDE Desktop Crash provides insights into terminal state recovery, which complements fixing input redirection errors. Similarly, Prevent fzf from screwing terminal settings highlights how certain interactive tools can alter terminal states, offering context on why proper input handling is critical for stable workflows.
Frequently Asked Questions
Why does my script work locally but fail in CI/CD pipelines?
Continuous Integration environments rarely allocate a TTY for build steps. Since there is no interactive terminal, any command attempting to read from/dev/tty will fail. You should configure your scripts to accept inputs via environment variables or configuration files in headless environments.
Can I use /dev/stdin instead of /dev/tty?
No,/dev/stdin is a symlink to whatever file descriptor 0 is currently pointing to, which is the redirected source causing the error. /dev/tty always points to the controlling terminal, making it the correct choice for interactive input.
What happens if I run this in a Docker container?
Docker containers do not have a TTY unless you start them with the-t flag. Without it, /dev/tty may not exist or be accessible. Use docker run -it to allocate a pseudo-TTY, allowing interactive reads to function correctly.
How do I handle passwords securely without prompting?
Never prompt for passwords in scripts meant for automation. Use environment variables exported before execution or pass secrets via secure mechanisms like Kubernetes secrets or AWS Parameter Store. Interactive prompts are inherently insecure in automated contexts.Does this error affect graphical applications launched from the terminal?
Graphical applications usually ignorestdin redirections unless they are CLI tools. However, if you launch a GUI app that spawns a background daemon expecting input, that daemon might fail. Check the application's documentation to see if it supports non-interactive modes.