Bug in /bin/sh -c

Michael "Ford" Ditto ditto at cbmvax.UUCP
Tue Nov 1 08:36:39 AEST 1988


In article <2508 at rtech.rtech.com> ralph at rtech.rtech.com (Ralph Harnden) writes:
>Is this a bug in /bin/sh on the UNIXPC, or am I ____?
>
>I type "/bin/sh -c ps -e" from a shell, and I get all of the
>garbage in /etc/profile and $HOME/.profile before I get ps.
>
>I do the same thing with ksh, and I just get ps, like I should.

But notice that in neither case does the -e argument get passed to ps.
This is because you are misusing the -c option:  -c takes exactly one
argument, the command to execute.  Any other arguments are interpreted
as more arguments to sh.  In other words, what you really wanted was:

	sh -c "ps -e"

Now, there is an inconsistency here, as you noticed...  /bin/sh
refuses to examine the remaining arguments after the -c arg, and just
stuffs them into its internal argv (aka $0 $*).  ksh, on the other
hand, continues parsing arguments normally, and accepts the "-e" as
the exit-on-error flag.  Now the funny thing here is that after this
argument processing is done, argv[0][0] is compared with '-' to see
if you are just logging in, and since sh put the "-e" in argv[0], it
decides you need your login actions done.  ksh grabbed the "-e" as
a ksh option, so it didn't get put in argv[].

BTW, ksh -c puts the non-option arguments starting in argv[1], while
sh puts them starting in argv[0].  This is an sh/ksh incompatibility
which can break scripts, although I would say ksh has the more
correct behavior (i.e., if an existing program uses
"sh -c {script} {scriptargs}", it is relying on erroneous behaviour
of /bin/sh).

I do use it interactively quite often, though, for things like this:

	find / -exec /bin/sh -c '[ -s $0 ]' {} \; -print

That wouldn't work if /bin/sh were replaced with ksh, so I avoid
such things in scripts I'm going to keep.

I hope you were all taking notes, because there will be a test next
period.   :-)
-- 
					-=] Ford [=-

"The number of Unix installations	(In Real Life:  Mike Ditto)
has grown to 10, with more expected."	ford at kenobi.cts.com
- The Unix Programmer's Manual,		...!sdcsvax!crash!elgar!ford
  2nd Edition, June, 1972.		ditto at cbmvax.commodore.com



More information about the Unix-pc.bugs mailing list