Course contentsShow
← Linux
Lesson 234 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Built-in vs Binary

Understand the performance implications of shell built-ins.

In this lesson, you will learn why choosing between a shell built-in and an external binary significantly impacts your script's execution speed.

The Shell’s Two Toolkits

When you run a command in your terminal, the shell has two ways to process it: it either performs the action itself using an internal built-in command, or it leaves the safety of its own memory to execute an external binary file (found in locations like /bin/ or /usr/bin/).

The Hidden Cost of Forking

To understand the performance difference, recall our previous discussion on Shell Forking Behavior.

When you execute an external binary, the shell must perform a "fork"—it creates a complete copy of itself, pauses, and then loads the new program from the disk into memory. This involves overhead: the operating system has to allocate memory, map the binary, and manage a new process.

In contrast, a built-in is part of the shell's own code. Running it requires no fork. The shell simply calls a function already loaded in memory.

A Concrete Example

Consider a simple task: printing text.

  • echo is a shell built-in.
  • /bin/echo is the external binary version.

If you write a loop that performs an operation 1,000 times, the difference becomes stark:

# Using the built-in (Fast)
for i in {1..1000}; do echo "Processing..."; done

# Using the external binary (Slow)
for i in {1..1000}; do /bin/echo "Processing..."; done

In the first example, the shell stays "home" and handles the request instantly. In the second, the shell must fork, execute, and wait for a child process to finish 1,000 separate times. In a complex script, this can turn a sub-second task into a multi-second bottleneck.

You can identify which version you are using by running the type command. For example, type cd will confirm it is a "shell builtin," while type ls will reveal it is a "hashed" (external) binary. Whenever you have the choice—especially inside loops—always favor the built-in to keep your script responsive.

Key Takeaway: Built-ins run inside the current shell process, whereas external binaries force the shell to spawn a new process, creating significant performance overhead.