The command built-in in Linux is part of most Unix-like shell environments (like bash and zsh). It is used to execute commands, bypass shell functions or aliases, and check the availability of commands in the environment.
- Bypasses shell aliases or functions: Ensures the actual binary/executable is run, rather than an alias or shell function of the same name.
- Verifies the existence of a command: Checks whether a command is available and where it resides in the system.
- Executes commands efficiently: Runs commands directly without applying shell functions or aliases.
command [options] [command_name] [arguments]-
-v: Displays the path to the command or the alias/function definition if it exists.command -v ls # Output: /bin/ls
-
-V: Provides a detailed description of the command, including whether it's an alias, function, or executable.command -V ls # Output: ls is /bin/ls
-
-p: Ignores functions and uses the PATH variable to locate the command.command -p ls -
--help: Displays help information forcommand.
-
Bypass Aliases or Functions: If
lsis aliased (e.g.,alias ls='ls --color=auto'), you can bypass it:command ls -
Check If a Command Exists: Useful in shell scripting to ensure a dependency is installed:
if command -v curl > /dev/null; then echo "curl is installed" else echo "curl is not installed" fi
-
Get Command Details: Determine whether a name refers to an alias, function, or executable:
command -V echo # Output: echo is a shell builtin
-
Use Default Binary Version: When a function with the same name exists:
ls() { echo "This is a function"; } command ls # Output: (runs the binary /bin/ls instead of the function)
-
Resolve the Path of a Command:
command -v python3 # Output: /usr/bin/python3
-
Debug a Script: Ensure the correct executables are being used:
command -V grep # Output: grep is /bin/grep
-
Scripting Dependency Checks:
if ! command -v git &> /dev/null; then echo "git is not installed. Please install it." exit 1 fi
- The
commandbuilt-in is particularly useful in scripts to ensure robust execution and proper resolution of commands. - Unlike external utilities like
which,commandis faster as it is a shell built-in and doesn’t spawn a new process.
By understanding command, you can write more precise and error-resistant shell scripts and manage your shell environment more effectively.