I want to learn to use the shell and was wondering why this didn't do as expected
Bill Jonas
plug-discuss@lists.plug.phoenix.az.us
Thu, 20 Feb 2003 13:14:14 -0700
--PBu/a+gn9/ndsyD5
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
On Thu, Feb 20, 2003 at 01:06:54PM -0700, Michael Havens wrote:
> [bmike1@localhost training]$ sort mypasswd |cat mypasswd
sort(1) sorts its standard input or a file named on the command line,
and sends the results to its standard output. In this case, you were
using the sorted output as input to cat(1), which didn't do anything
with it, preferring instead to display the contents of the file you
named.
> which I found was not sorted. So I thought that the sort had to be rewrit=
ten=20
> to the file and then I would look at it.
That's true.
> [bmike1@localhost training]$ sort mypasswd >mypasswd |cat mypasswd
=2E..
> [bmike1@localhost training]$ cat mypasswd
>=20
> which gave me the prompt again. Why did it do this?
When you use redirection operators (ie, >, <, >>, etc.), the shell
prepares the redirected files *before* it runs the commands. What
happens with "sort mypasswd >mypasswd" is that the shell notices the >
and determines that you want to redirect the output to "mypasswd". So
it finds that there is already a file named mypasswd and truncates the
length to zero. *Then* the shell runs the sort(1) command you
specified. sort(1) finds a zero-length file and dutifully sorts it,
correctly producing no output. (The "|cat mypasswd" isn't useful, but
by way of explanation, by the time cat(1) sees mypasswd, it's already
empty, too.)
What you probably want is something like this:
$ head -20 /etc/passwd |sort >mypasswd; cat mypasswd
Or if you already have the file created:
$ mv mypasswd mypasswd.old && sort mypasswd.old >mypasswd; cat mypasswd
Short summary: Don't use the same file for both input and output, since
the shell prepares the I/O streams and corresponding files before it
runs the command(s).
--=20
Bill Jonas * bill@billjonas.com * http://www.billjonas.com/
"It's a dangerous business, Frodo, going out your front door. You step
into the Road, and if you don't keep your feet, there is no knowing
where you might be swept off to." -- Bilbo Baggins
--PBu/a+gn9/ndsyD5
Content-Type: application/pgp-signature
Content-Disposition: inline
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
iD8DBQE+VTcUdmHcUxFvDL0RAmtMAJ9lTehm4mjYsvrDUYTPhzsmbxvkUACeLlXO
oQTQKWsieo4vqR/BNRPl1O4=
=YrpV
-----END PGP SIGNATURE-----
--PBu/a+gn9/ndsyD5--