How to determine if a command is built-in or external in Linux?

Determining If a Command is Built-in or External in Linux

In the Linux operating system, commands can be classified into two main categories: built-in commands and external commands. Understanding the difference between these two types of commands is essential for effectively using and troubleshooting the Linux shell.

Built-in Commands

Built-in commands are commands that are part of the shell itself, meaning they are directly executed by the shell without the need to launch a separate process. These commands are typically used for shell-specific tasks, such as managing the shell's environment, controlling the flow of execution, and performing basic file and directory operations.

Some examples of built-in commands in Linux include:

  • cd (change directory)
  • echo (print text to the console)
  • exit (exit the current shell session)
  • export (set an environment variable)
  • pwd (print the current working directory)

To determine if a command is a built-in command, you can use the type command in the Linux shell. For example, to check if the cd command is a built-in command, you can run:

type cd

The output will indicate that cd is a shell builtin.

cd is a shell builtin

External Commands

External commands, on the other hand, are programs that are stored as separate executable files on the file system. These commands are not part of the shell itself, and the shell needs to launch a new process to execute them.

Examples of external commands in Linux include:

  • ls (list directory contents)
  • cat (concatenate and print files)
  • grep (search for patterns in files)
  • mkdir (create a new directory)
  • rm (remove files or directories)

To determine if a command is an external command, you can use the type command again, but this time, it will indicate that the command is found in the file system.

type ls

The output will show the full path to the executable file for the ls command.

ls is /usr/bin/ls

Additionally, you can use the which command to locate the path of an external command.

which ls

The output will be the same as the type command, showing the full path to the executable file.

/usr/bin/ls

By understanding the difference between built-in and external commands, you can more effectively use and troubleshoot the Linux shell, as well as understand the underlying mechanisms of how commands are executed.

graph TB A[Command] --> B(Built-in) A[Command] --> C(External) B --> D[Executed by the shell] C --> E[Executed as a separate process]

In the diagram above, we can see that a command in Linux can be either a built-in command, which is executed directly by the shell, or an external command, which is executed as a separate process.

0 Comments

no data
Be the first to share your comment!