Bash Built-in Commands

Essential commands built into the shell

⚡ What are Built-in Commands?

Built-in commands are part of the bash shell itself, not separate programs. They execute faster than external commands and can modify the shell environment directly. Understanding these commands is essential for effective shell scripting.


# Check if command is built-in
type cd

# List all built-in commands
help
                                    

Output:

cd is a shell builtin
GNU bash, version 5.1.16

Essential Built-ins

📁

cd

Change directory

cd /home
📄

echo

Display text or variables

echo "Hello"
📖

read

Read user input

read name
🚪

exit

Exit the shell

exit 0

🔹 Directory Navigation

Efficient directory navigation commands are the foundation of productive command‑line work. cd changes the current working directory—use cd ~ to go home, cd - to toggle to the previous directory. pwd prints the absolute path of your current location. pushd and popd manage a directory stack for jumping between locations. Mastering these commands, along with tab completion and pathname expansion, dramatically speeds up file system traversal, script writing, and server administration tasks.

# Change to directory
cd /usr/local

# Go to home directory
cd ~
cd  # Same as cd ~

# Go to previous directory
cd -

# Print current directory
pwd

# Change to parent directory
cd ..

# Change to root directory
cd /

Output:

/usr/local
/home/user
/usr/local
/home/user/projects

🔹 Output Commands

The echo and printf commands are essential for displaying text, variables, and formatted output in shell scripts. echo is simple and ideal for quick messages, variable expansion, or writing to files. printf offers C‑style formatting for precise control over output layout, including padding, decimal places, and column alignment. Both commands are indispensable for user feedback, debugging scripts by printing variable states, generating structured data (like CSV), and creating dynamic configuration files. Understanding their flags and escape sequences enhances script professionalism and reliability.

# Simple echo
echo "Hello World"

# Echo without newline
echo -n "No newline"

# Echo with escape sequences
echo -e "Line 1\nLine 2\tTabbed"

# Print variables
NAME="John"
echo "Hello, $NAME"

# Printf with formatting
printf "Name: %s, Age: %d\n" "John" 30

# Printf with padding
printf "%-10s %5d\n" "Item" 100

Output:

Hello World
No newlineLine 1
Line 2	Tabbed
Hello, John
Name: John, Age: 30
Item         100

🔹 Input Commands

The read command captures user input or file content, enabling interactive and dynamic shell scripts. It can assign input to single or multiple variables, read entire lines, use custom prompts (-p), set timeouts (-t), and even read from file descriptors. This functionality is crucial for creating user‑friendly scripts—like installation wizards, configuration tools, or menus—that respond to live input. Combined with conditionals and loops, read transforms static scripts into adaptable programs that can handle a wide range of runtime inputs and scenarios.

# Read single variable
read name
echo "Hello, $name"

# Read multiple variables
read first last
echo "Name: $first $last"

# Read with prompt
read -p "Enter age: " age

# Read password (hidden)
read -sp "Password: " pass

# Read with timeout
read -t 5 -p "Quick (5s): " answer

# Read entire line
read -r line

Output:

John
Hello, John
John Doe
Name: John Doe
Enter age: 25
Password: ******
Quick (5s): yes

🔹 Variable Commands

Variable commands in Bash are essential for shell environment and script configuration management. Key built-in commands like export, declare, readonly, and unset allow you to create, modify, secure, and remove variables. Exporting variables makes them available to child processes, ensuring proper inheritance. Declaring types adds safety, while read-only variables prevent accidental changes. Effective variable management is fundamental for creating portable, maintainable scripts that adapt to different execution environments and user configurations.

# Set variable
NAME="John"

# Export to environment
export PATH="/usr/local/bin:$PATH"

# Declare integer
declare -i count=10

# Declare array
declare -a fruits=("apple" "banana")

# Declare read-only
declare -r CONSTANT="fixed"

# Unset variable
unset NAME

# Show all variables
declare -p

Output:

declare -- NAME="John"
declare -x PATH="/usr/local/bin:/usr/bin"
declare -i count="10"
declare -a fruits=([0]="apple" [1]="banana")

🔹 Control Flow Commands

Control flow commands determine the execution path of your Bash scripts using conditions and loops. Commands like if, case, for, while, and until let you test expressions and repeat actions. The break and continue statements manage loop execution, while return exits functions with specific codes. This logic allows scripts to make decisions, handle different inputs, automate repetitive tasks, and respond dynamically to system states, forming the backbone of any complex automation.

# Test command
test -f file.txt
[ -f file.txt ]  # Same as test

# If statement
if [ -f file.txt ]; then
    echo "File exists"
fi

# Case statement
case $1 in
    start) echo "Starting" ;;
    stop) echo "Stopping" ;;
esac

# Break from loop
for i in {1..10}; do
    [ $i -eq 5 ] && break
done

# Continue loop
for i in {1..5}; do
    [ $i -eq 3 ] && continue
    echo $i
done

Output:

File exists
Starting
1
2
4
5

🔹 Job Control Commands

Job control commands manage the execution of processes, allowing multitasking within the shell. Using commands like jobs, fg, bg, and wait, you can list running jobs, switch processes between foreground and background, and pause execution until completion. This is vital for running long tasks without blocking your terminal, handling multiple operations simultaneously, and gracefully managing script execution flow. Mastering job control enhances productivity and is key for sophisticated process orchestration in scripts.

# Run command in background
sleep 100 &

# List jobs
jobs

# Bring job to foreground
fg %1

# Send job to background
bg %1

# Wait for background jobs
wait

# Disown job (remove from job table)
disown %1

# Kill job
kill %1

Output:

[1] 12345
[1]+  Running    sleep 100 &
[1]+  Running    sleep 100 &
[1]+  Done       sleep 100

🔹 History Commands

Bash history commands provide efficient access and manipulation of your command-line history. Use history to view the list, !! to repeat the last command, and !n to execute a specific historical command. Searching with Ctrl+R or using history | grep finds past commands quickly. You can also clear history with history -c. These tools save significant time, reduce retyping errors, and help audit or reuse complex commands, boosting overall command-line proficiency and workflow speed.

# Show command history
history

# Show last 10 commands
history 10

# Execute command by number
!123

# Execute last command
!!

# Execute last command starting with 'git'
!git

# Search history
history | grep "docker"

# Clear history
history -c

Output:

  121  ls -la
  122  cd projects
  123  git status
  124  docker ps
git status
docker ps

🔹 Utility Commands

Built-in utility commands perform essential operations that enhance shell productivity and introspection. Commands like type check if a command is built-in or external, help displays documentation, eval executes arguments as a single command, and alias creates command shortcuts. Others like command bypass aliases/functions, and exec replaces the shell. These utilities are indispensable for writing robust scripts, debugging, and creating a more efficient and personalized command-line environment.

# Check command type
type ls
type cd

# Get help for built-in
help cd

# Evaluate expression
let "result = 5 + 3"
echo $result

# Execute command from string
eval "echo Hello"

# Create alias
alias ll='ls -la'

# Remove alias
unalias ll

# Source script
source script.sh

Output:

ls is aliased to `ls --color=auto'
cd is a shell builtin
8
Hello
total 24
drwxr-xr-x 2 user user 4096

🧠 Test Your Knowledge

Which command changes the current directory?