Tuesday, April 24, 2012

A different use of cat


> cat > hello.py << EOF
> print "Hello, world!"
> EOF
> python hello.py
Hello, world!
> more hello.py
print "Hello, world!"
>

How does this work? According to the man page for cat, if

file is a single dash (`-') or absent, cat reads from the standard input.
The ">" redirects to a file as usual.

The "<<" is special. The whole construct is called a "here document." I found more about it including its proper name here, which leads to a wikipedia entry.

Note that any symbol not present by itself on a line in the desired text will work for termination. Here's a rather silly sequence in which it took me a while to enter the single character 'X' to stop input:

> cat > x.txt << X
> x
> cat > x.txt << XY
> cat > x.txt << XYZ
> print me
> XYZ
> cat > x.txt << X
> hi
> X
> more x.txt
x
cat > x.txt << XY
cat > x.txt << XYZ
print me
XYZ
cat > x.txt << X
hi
>

Quick Unix: a brief look at Unix stuff that I find interesting and not too obvious.