2024-12-13
Shell built-ins are functions or commands implemented within the shell’s code. They’re typically faster than external commands because they avoid the overhead of process creation and execution. Common shells like Bash, Zsh, and Ksh each have their own sets of built-in commands. While some built-ins are common across different shells, others might be unique to a specific shell.
Let’s look at some widely used built-in commands:
cd
(Change Directory)The cd
command is arguably the most frequently used built-in. It changes the current working directory.
Examples:
cd /home/user/documents
: Changes the directory to /home/user/documents
.cd ..
: Moves up one directory level.cd -
: Returns to the previously accessed directory.cd ~
: Goes to your home directory.pwd
(Print Working Directory)pwd
displays the current working directory path.
Example:
pwd
echo
(Display Text)The echo
command prints text to the standard output (usually your terminal).
Examples:
echo "Hello, world!"
echo "The current directory is: $(pwd)"
Note the use of $(pwd)
for command substitution – it executes pwd
and inserts its output into the echo
command.
exit
(Exit Shell)exit
terminates the current shell session. You can optionally provide a status code; a non-zero code usually indicates an error.
Examples:
exit
exit 0 # Successful exit
exit 1 # Error exit
export
(Set Environment Variables)export
sets environment variables, making them accessible to child processes.
Example:
export MY_VARIABLE="Hello from export"
echo $MY_VARIABLE # Accessing the variable
unset
(Unset Variables)The unset
command removes variables from the shell’s environment.
Example:
unset MY_VARIABLE
echo $MY_VARIABLE # The variable is now undefined
history
(Show Command History)history
displays a list of previously executed commands.
Example:
history
alias
(Create Command Aliases)alias
creates shortcuts for frequently used commands.
Example:
alias la='ls -la' # Create an alias 'la' for 'ls -la'
la # Use the alias
source
or .
(Execute a Script)The source
command (or its dot operator equivalent, .
) executes a shell script in the current shell environment, making any changes within the script directly visible.
Example:
Let’s say you have a script named my_script.sh
containing:
export MY_SCRIPT_VAR="Value from script"
To execute and import the variable:
source my_script.sh
echo $MY_SCRIPT_VAR
These examples demonstrate only a subset of shell built-in commands. Each shell offers a broader range of functionalities. Exploring your shell’s built-in command documentation (often accessible via help
or man
) will improve your Linux proficiency. Remember that effective use of built-ins streamlines your workflows and improves efficiency.