Created
February 2, 2018 03:07
-
-
Save mervick/95aa8f09afeaf0f6278b50a96b8e02ac to your computer and use it in GitHub Desktop.
Detect pipe/file input in Bash / shell script
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
# How to detect whether input is from keyboard, a file, or another process. | |
# Useful for writing a script that can read from standard input, or prompt the | |
# user for input if there is none. | |
# Source: http://www.linuxquestions.org/questions/linux-software-2/bash-scripting-pipe-input-to-script-vs.-1-570945/ | |
if readlink /proc/$$/fd/0 | grep -q "^pipe:"; then | |
# Pipe input (echo abc | myscript) | |
elif file $( readlink /proc/$$/fd/0 ) | grep -q "character special"; then | |
# Terminal input (keyboard) | |
else | |
# File input (myscript < file.txt) | |
fi | |
# ALTERNATIVE: | |
# In Bash you can also use test -t to check for a terminal: | |
if [ -t 0 ]; then | |
# Terminal input (keyboard) - interactive | |
else | |
# File or pipe input - non-interactive | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment