command

2024-12-13

Understanding Shell Built-ins

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:

1. cd (Change Directory)

The cd command is arguably the most frequently used built-in. It changes the current working directory.

Examples:

2. pwd (Print Working Directory)

pwd displays the current working directory path.

Example:

pwd

3. 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.

4. 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

5. 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

6. 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

7. history (Show Command History)

history displays a list of previously executed commands.

Example:

history

8. 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

9. 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.