xv6, line by line
user/echo.c

user/echo.c

C · 19 lines · annotated 100% · user program / library · upstream

About this file

echo prints its arguments to standard output, separated by single spaces and followed by a newline: echo hello world prints hello world. Combined with the shell’s redirection it is the quickest way to create a small file (echo hi > f).

The program shows how arguments reach a process. The shell splits the command line at spaces and passes the words to exec; the kernel copies them onto the new program’s user stack (kexec), and they arrive here as argc and argv. Since the shell has already split the words, any run of spaces between them is gone: echo a b prints a b. xv6’s shell does not understand quotes either, so echo 'a b' prints 'a b'.

The only system calls are write (sys_write) and exit (sys_exit).

Read before: user/cat.c. Read next: user/sh.c, to see how the shell builds argv.

5int
6main(int argc, char *argv[])
7{
8 int i;
10 for (i = 1; i < argc; i++) {
12 if (i + 1 < argc) {
13 write(1, " ", 1);
14 } else {
15 write(1, "\n", 1);
16 }
17 }
18 exit(0);