Friday, November 25, 2005

Fancier Redirection

The shell lets you do a lot of fancy redirection without much work. I'll show many examples as we go along, but here are a couple you'll use frequently.

Q: How do I put stdout and stderr into the same file?
# first, let's make sure X exists and Y doesn't
> X
rm Y

# now some experiments
# try these on the command line
ls X Y
ls X Y > OUT
ls X Y 2> ERR
ls X Y &> BOTH
ls X Y > AMANDOI 2>&1 # Sometimes you see this form instead. It's the same as &>.
# We'll explain why another time.
# Any Romanians reading this?
If you didn't do the last commands by recalling and editing earlier commands,
I suggest going back and trying that out. Make using and editing the command history a habit now, not later.

Q: What if I don't want to overwrite files? What if I want to tack onto the end of a file instead?
#!/bin/bash
# > overwrites, >> appends

echo hello > /tmp/$$
echo world >> /tmp/$$
cat /tmp/$$

rm -f /tmp/$$
This script logs network activity, once an hour.
#!/bin/bash
while true
do
date
ruptime
sleep $[ 60 * 60 ] # an hour's worth of seconds
echo # blank line between each timepoint
done >> /tmp/LOG

0 Comments:

Post a Comment

<< Home