Determine If Shell Input is Coming From the Terminal or From a Pipe
Working on a little script the other day I had the need to determine if the input to the script was coming from a pipe or from the terminal. Seems like a simple enough thing to determine but nothing jumped immediately to mind and a quick internet search didn't help much either. After a bit of pondering I came up with two solutions: the stat command and using information from the proc file system.
The first solution uses the stat command to determine what type of file is connected to standard input. First we find out what is connected to standard input:
stdin="$(ls -l /dev/fd/0)"
stdin="${stdin/*-> /}"
The file /dev/fd/0 is the standard input, which is a symbolic link. So we use ls to get the file it's linked to. Then we remove everything that matches *-> from the front of the value, that leaves us with the linked to file.
Now we use stat to get the file type:
ftype="$(stat --printf=%F $stdin)"
Then we just test the file type:
if [[ "$ftype" == 'character special file' ]]; then
echo Terminal
elif [[ "$ftype" == 'regular file' ]]; then
echo Pipe: $stdin
else
echo Unknown: $stdin
fi
We can test it via:
$ sh ckpipe.sh
Terminal
$ sh ckpipe.sh <ckpipe.sh
Pipe: .../ckpipe/ckpipe.sh
The next solution I came up with involves using information from the proc file system. In the proc file system the files for each process appear in the directory /proc/PROCESS_ID/fd (for the current process the special directory /proc/self/fd can be used):
$ ls -la /proc/self/fd
total 0
dr-x------ 2 mitch users 0 2010-02-10 11:04 .
dr-xr-xr-x 7 mitch users 0 2010-02-10 11:04 ..
lrwx------ 1 mitch users 64 2010-02-10 11:04 0 -> /dev/pts/2
lrwx------ 1 mitch users 64 2010-02-10 11:04 1 -> /dev/pts/2
lrwx------ 1 mitch users 64 2010-02-10 11:04 2 -> /dev/pts/2
lr-x------ 1 mitch users 64 2010-02-10 11:04 3 -> /proc/29328/fd
As before we need the name of file that is linked to, so we get that with:
stdin="$(ls -l /proc/self/fd/0)"
stdin="${stdin/*-> /}"
From there we can just test to see if it's linked to a /dev/pts file:
if [[ "$stdin" =~ ^/dev/pts/[0-9] ]]; then
echo Terminal
else
echo Pipe: $stdin
fi
We test this the same way:
$ sh ckpipe2.sh
Terminal
$ sh ckpipe2.sh <ckpipe2.sh
Pipe: .../ckpipe/ckpipe2.sh
| Attachment | Size |
|---|---|
| ckpipe_sh.txt | 263 bytes |
| ckpipe2_sh.txt | 156 bytes |
Mitch Frazier is an Associate Editor for Linux Journal.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Download the Free Red Hat White Paper "Using an Open Source Framework to Catch the Bad Guy"
- Home, My Backup Data Center
- Tech Tip: Really Simple HTTP Server with Python
- Please correct the URL for Salt Stack's web site
54 min 2 sec ago - Android is Linux -- why no better inter-operation
3 hours 9 min ago - Connecting Android device to desktop Linux via USB
3 hours 37 min ago - Find new cell phone and tablet pc
4 hours 35 min ago - Epistle
6 hours 4 min ago - Automatically updating Guest Additions
7 hours 13 min ago - I like your topic on android
7 hours 59 min ago - Reply to comment | Linux Journal
8 hours 21 min ago - This is the easiest tutorial
14 hours 35 min ago - Ahh, the Koolaid.
20 hours 14 min ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
-t / isatty / ioctl
I have had the same problem recently and had to implement it in C too -- the solution: isatty
I found out that -t and isatty uses an ioctl to achieve the result, which led me to the following C solution:
#include #include #include #include #define STDIO 0 int main() { struct termios NewTermios; if (isatty(STDIO)) printf("Input from a terminal (according to isatty)\n"); else printf("Input NOT from a terminal (according to isatty)\n"); if (ioctl(STDIO, TCGETS, &NewTermios) == 0) printf("Input from a terminal (according to ioctl)\n"); else printf("Input NOT from a terminal (according to ioctl)\n"); }Really nice post
I really enjoyed this one, not only because it's a useful thing but makes you remind you how you can play with bash (and Linux) as a Lego.
Apart from the original post the comments are neat too :)
Long live to the community.
Actually both solutions are the same
$ ls -l /dev/fd
lrwxrwxrwx 1 root root 13 2010-02-12 14:33 /dev/fd -> /proc/self/fd
/dev/fd is just a symlink to /proc/self/fd
tty detection in one line
tty -s && echo "Yes, we are on a tty! zomg Ponies!" || echo "Nope, we're not on a tty and it's cool."I use something like this to detect whether I'm on a tty. Not useful for pipe detection, but hey.
L8N buglet in your first solution
The stat command (or tty) will localise its output and fail unless the local is a suitable en one, so you need to prefix it with something like: LC_ALL=C. Bad enough, but typical in shell programming... :(
/dev/pts is good only for remote shells or shells in X11 windows
> if [[ "$stdin" =~ ^/dev/pts/[0-9] ]]; then
> echo Terminal
> else
> echo Pipe: $stdin
> fi
The above will not work for shell sessions on (local) virtual consoles.
HI
Well It is not so simple as it's seems to be.I think before reading this post many people must have been unaware from this so you have helped them by providing this quite cool info to them.
"So we use ls to get the file it's linked to"
I agree the "tty" command might be the better solution here, but with regard to the general situation of following a symbolic link:
> stdin="$(ls -l /dev/fd/0)"
> stdin="${stdin/*-> /}"
That looks ugly to me.
how about:
stdin="$(readlink -f /dev/fd/0)"
BTW, this also seems to work:
- Jeff
Readlink
Agreed, readlink is better.
Mitch Frazier is an Associate Editor for Linux Journal.
This reminds me of perl (tmtowdi) ...
This post and its comments remind me of that perl saying which I guess applies to the shell as well - there's more than one way to do it (TMTOWTDI) ...
regards
tty gets it done
Just like Jim Helm, I use tty to test for this. A quick and dirty function like:
am_I_on_a_terminal() { if [[ $(tty -s ; echo ${?}) == 0 ]] ; then ANSWER=1 else ANSWER=0 fi printf "%d" "${ANSWER}" } if [[ $(am_I_on_a_terminal) == 1 ]] ; then printf "%s\n" "I am on a terminal" else printf "%s\n" "I must be runnig from cron" fi exit 0Can accomplish the task.
RV
Check $- to know if the shell is interactive
Depending on what you want to do, you can check if the character "i" is present in the special bash variable $-
if echo "$-" | grep -q i; then
echo "The shell is interactive"
else
echo "Non-interactive shell (closed stdin, file, pipe, ...)"
fi
two words
man tty
Thanks
Another good way. The tty command returns "not a tty" when the input is coming from a pipe.
Mitch Frazier is an Associate Editor for Linux Journal.
Shell test
Did you try
test -t /proc/self/fd/0(or just[ -t /proc/self/fd/0 ])? We could define:function isTTY() { local path="${1:-/proc/self/fd/0}" [ -t "$path" ] }test -t
The -t option (which I just learned about from the comment below) tests a file-descriptor, not a file. So you can't do what you're suggesting, checking a path, you would need to determine the file-descriptor. In the case of stdin, you just use "0":
function isTTY() { local fd="${1:-0}" [ -t "$fd" ] }Mitch Frazier is an Associate Editor for Linux Journal.
What's wrong with -t?
Why wasn't the conditional expression "if [ -t 0 ] ; ..." (which is stat-based) sufficient?
-t refined
According to this reference:
http://tldp.org/LDP/abs/html/intandnonint.html
it proposes:
if [[ -t "$fd" || -S /dev/stdin ]]
then
echo interactive
else
echo non-interactive
fi
so that it's valid even when you are connected via ssh.
Nothing
Nothing's wrong with that, I just wasn't aware of it. Like I said it seemed like it ought to be simple and it would have been had I known about that.
Mitch Frazier is an Associate Editor for Linux Journal.