168 points · by dchest · 15y ago · 86 comments
$type echo
echo is a shell builtinIt's calling "write", which is a system call. Without the buffer, it would call write once for argv, and once for the newline if nflag is not set. Calling a system call twice would result in twice as many context switches, and thus be very slightly slower.
Speaking of clever tricks, would it be faster or slower to use c99's variable-length arrays instead of malloc?
But a single malloc is nothing compared to the cost of a context switch into kernel mode.
int main (int argc, const char * argv[])
{
for( int i = 1; i < argc; ++i)
{
((char *)argv[i])[-1] = ' ';
}
size_t len = strlen(argv[argc - 1]);
((char *)argv[argc - 1])[len] = '\n';
write(1, argv[1], argv[argc - 1] - argv[1] + len + 1);
return EXIT_SUCCESS;
}V6: http://www.bsdlover.cn/study/UnixTree/V6/usr/source/s1/cat.s... V7: http://www.bsdlover.cn/study/UnixTree/V7/usr/src/cmd/cat.c.h... Plan 9: http://plan9.bell-labs.com/sources/plan9/sys/src/cmd/cat.c BSD: http://www.koders.com/c/fidF501905968D8BE7BBDD355C3C8DB62804... GNU: http://git.savannah.gnu.org/cgit/coreutils.git/plain/src/cat...
However, unlike the minimal version often seen, GNU Hello processes its argument list to modify its behavior, supports greetings in many languages, and so on. The primary purpose of GNU Hello is to demonstrate how to write other programs that do these things; it serves as a model for GNU coding standards and GNU maintainer practices."
(alluding to a quote from him that I can’t source, “One of my most productive days was throwing away 1000 lines of code.”)
See also, "UNIX Style, or cat -v Considered Harmful" (http://harmful.cat-v.org/cat-v/).
It seems telling that the GNU echo's source is "derived from code echo.c in Bash."
For example, instead of cat -v, you'd have a second utility called, 'nonprint' which would just translate non-printing chars, and you'd call it using
cat file1 file2 | nonprintIf you need more features from a basic utility like echo or cat you should create your own version, maybe with a slightly different name, and leave the original as it is.
All of these tools are intended to be composable, analogous to functions. 'cat -v' is like a function with too many arguments, one that does too much. If you need, for example, to allocate a block of zero'd memory, you don't add new flags to malloc(); you use memset() after allocation, you write a for loop, or you use calloc().
Likewise, the basic tools available on Unix can and should be thought of as functions, which take some number of arguments, and the implicit argument of an input channel. They produce as their output an integer as a return value and two output channels, stdout and stderr. Making a function that does too much (and this is as subjective for functions as it is for command-line tools) is known to be bad practice, but for the shell, it is often misunderstood. To misunderstand this is to misunderstand the core principals of the Unix environment.
It has nothing to do with the typical non-programmer user. On, say, Linux or OSX, the user doesn't write functions or talk to the shell very often. They click buttons in a GUI that doesn't in a meaningful sense offer composable programs, and it's an inefficient but simple way to interact with the machine, a way that matches their habits and understanding. cat, echo, sed, and awk aren't for these users; they're for programmers, and the typical user does not know or care whether cat can show non-printing characters, but as a programmer, I certainly care about a clean design for my environment.
The "-n" special case opened the floodgates for many more options. And what if I actually wanted to print "-n"? There's no way to do it.
Good point.I first tried "echo \-n", and "echo -- -n". No luck. I get the correct visual effect with "echo - ^Hn" (^H generated with ^V, backspace), but the embedded backspace is still actually part of the output :P "echo - ^Hn | col" strips it. Seems like quite an oversight, really, and is prime example of how bugs sneak into code via features.
edit: ilikejam solved it w/o leaning on other tool. As he said "not pretty", but simpler than what I have: http://news.ycombinator.com/item?id=2781034
% env POSIXLY_CORRECT=1 echo -n
-n
Also note that if your shell is Bash, then your echo is a built-in: % type echo
echo is a shell builtin
That's why 'env' is necessary. kamloops$ uname -s
NetBSD
kamloops$ echo $0
sh
kamloops$ env POSIXLY_CORRECT=1 echo -n
kamloops$dave@cronus $ ./echo -n "-n
dave@cronus > "
-n
dave@cronus $
Not pretty, though.
bash-3.2$ echo -n -n foo
foobash-3.2$
Like always with echo -n, no matter what you try, it's not portable.[dave@mini ~]$ echo -n "-n foo
> "
-n foo
[dave@mini ~]$
Easy!
If a system has printf, and I think all recent Unix-like systems do, then it works at least 98% the same.
http://www.opensource.apple.com/source/shell_cmds/shell_cmds...
It's close to the FreeBSD implementation.
-r recursive (i.e., it should always be recursive mode if a command operates on files, and should always exist if it makes sense for that command)
-v verbose
-s sort
-i ignore case
-q quiet (suppress output)
If there were, say, 20 well-chosen standard flags (and they were enforced) it could have given the UNIX tools another level of nice regularity.
So rather than this:
void test()
{
int *x = malloc(1000);
int *y = malloc(1000);
for(int i = 0; i < 999; i++) {
if(badThing) {
free(x);
free(y);
return;
}
doStuff()
if(otherBadThing) {
free(x);
free(y);
return;
}
}
free(x);
free(y);
return;
}
You'd have: void test()
{
int *x = malloc(1000);
int *y = malloc(1000);
for(int i = 0; i < 999; i++) {
if(badThing)
goto ret;
doStuff()
if(otherBadThing)
goto ret;
}
ret:
free(x);
free(y);
return;
} void do_stuff(char *name) {
char *my_name = strdup(name);
if (condition_signalling_no_work()) goto done;
if (do_something_with(my_name)) goto done;
...
done:
free(my_name);
return;
}
If it helps think of it as a finally block. The function does some things and no matter what it has to run that block at the end.The way it is used in that code is pretty horrible, IMO, and splitting it into functions and using "return" in place of goto would have been far better.
[1] http://git.savannah.gnu.org/cgit/bash.git/plain/builtins/ech... http://git.savannah.gnu.org/cgit/bash.git/plain/support/rech... http://git.savannah.gnu.org/cgit/bash.git/plain/support/zech...
> while still doing nothing new
Really? So the GNU implementation is an exact match for the functionality of the SysV implementation? If so, I have a bridge I'd like to sell you...