CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 1 min read

Built-in commands

In plain words: The command cd changes the current working directory: the folder from which relative file names are resolved. Each process has its own. The shell cannot hand cd to a child. A child would change its own directory and then end, and the shell's directory would stay the same. The test below proves it:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
    if (fork() == 0) { chdir("/usr"); _exit(0); }
    wait(NULL);
    char b[256];
    getcwd(b, sizeof b);
    printf("parent still in %s\n", b);
    return 0;
}

The output on the test machine was parent still in /tmp/ost1. The child moved to /usr, and the parent did not.

A command that must change the shell's own state is therefore a built-in, run by the shell itself with no fork. cd and exit are such commands, as are export (change an environment variable) and ulimit. In the session above, the line cd /tmp followed by pwd printed /tmp, because cd ran inside the shell.

Built-in command

A built-in command is a command that the shell executes by itself, within its own process, instead of starting another program. Built-ins exist for commands that must change the shell's own state, such as its current directory.

Example: cd /tmp calls chdir in the shell process, so every later command the shell starts runs from /tmp.

Check yourself: 1. Why does a child's chdir not affect the parent? 2. Name two built-in commands. 3. Is ls a built-in?