I guess this is obvious to most people but it took me quite a while to dig it out on the internet. I wanted my bash script to be able to read from standard input like cat sourcefile.txt|bash myscript.bash
. It turns out the standard input can be read from /dev/stdin
. So if I wanted to sort
the standard input, myscript.bash would look like: sort /dev/stdin
I think this is probably basic UNIX knowledge but I’m not a programmer.
J | 11-Jun-07 at 9:49 am | Permalink
It’s unnecessary to call “bash myscript.bash”
Set your script executable:
chmod +x myscript.bash
and then run it as:
cat sourcefile.txt | ./myscript.bash
ScottS-M | 11-Jun-07 at 10:13 am | Permalink
That’s true. I tend to be lazy and just call bash explicitly instead of using chmod and adding
#!/bin/bash
to the first line of the script.firebush | 28-Jun-08 at 11:24 am | Permalink
Thanks, this was helpful.
cool | 22-Oct-08 at 6:35 pm | Permalink
Thanks to you I was able to use my google-fu and find the answer right away.
I’m going to change my script so that if $1 is “”
# ($1 is the first argument passed to the script)
then it reads from /dev/stdin
That should let me cat up a bunch of logfiles and send them all to my parser without saving them as a file first.
Tux | 09-Jun-10 at 1:04 pm | Permalink
Thank you so much. I was trying for an hour now until I found this page and finally made my script work.
Jeff Schroeder | 16-Jul-10 at 3:41 pm | Permalink
@J from 2007: If you’re going to correct someone, at least try a little harder. You win one of the ancient Unix “Useless Use of Cat” awards.
This is more succinct and avoids a useless fork/execve of cat
./myscript.bash < sourcefile.txt
enjoy :)