build-a-shell / lesson-08.md
Lesson 08 · Builtins

pwd

The shell always has a current working directory, and `pwd` prints it. It is a small builtin, but you need it today so you can see the effect of `cd` tomorrow.

The goal

Implement the `pwd` builtin so it prints the shell's current working directory.

Start here - the target
TO DO
Scenario: Printing the working directory
Giventhe shell's current working directory is "/tmp"
Whenthe command "pwd" runs
Thenit prints "/tmp" followed by a newline
Andthe last status is 0
Background

Every process has a current working directory - the folder that relative paths are resolved against - and the shell is no exception. pwd (“print working directory”) simply asks the operating system for that path and echoes it. It is about as small as a builtin gets.

Two reasons it comes now. First, it must be a builtin for the same reason cd will be: it reports the shell’s directory, and a child process has its own copy. Second, it is your window onto tomorrow’s work - once cd can change the directory, pwd is how you will confirm it actually moved. Build the observer before the thing it observes.

Make it work
if (strcmp(words[0], "pwd") == 0) {
char buf[PATH_MAX];
getcwd(buf, sizeof buf);
printf("%s\n", buf);
last_status = 0;
return; // handled as a builtin
}
Further Reading

POSIX shell utilities: pwd.

CheckpointDONE
Your shell can report where it is. Commit and stop here.