Setting Up Bash

Summary: in this tutorial, you will learn get bash installed and configured on linux, macos, or windows. set up your terminal, customize your prompt, and learn essential keyboard shortcuts.

Setting Up Bash

Before we start learning commands, let's make sure you have Bash properly installed and configured. A properly set up terminal environment makes learning faster and more enjoyable.

Why setup matters:

  • The right terminal: Modern terminals provide features like tabs, split panes, and better copy/paste that significantly improve productivity
  • Bash version: Newer versions have bug fixes, performance improvements, and new features
  • Customization: A personalized prompt, aliases, and keyboard shortcuts save hours of typing
  • Compatibility: Ensure your environment works with tutorials and documentation you'll encounter

This guide covers Linux, macOS, and Windows (via WSL), so regardless of your operating system, you'll have a professional Bash environment.

Bash on Linux

Great news—Bash comes pre-installed on virtually every Linux distribution!

Verify Your Installation

Open your terminal and type:

# Check if Bash is installed and its version
bash --version
 

You should see something like:


GNU bash, version 5.2.15(1)-release (x86_64-pc-linux-gnu)

Check Your Default Shell

# See what shell you're currently using
echo $SHELL
 
# List all available shells on your system
cat /etc/shells
 

Switch to Bash (if needed)

If your default shell isn't Bash:

# Change your default shell to Bash
chsh -s /bin/bash
 
# You'll need to log out and back in for the change to take effect
 
TerminalFeaturesBest For
GNOME TerminalBuilt into GNOME, tabs, profilesUbuntu/Fedora users
KonsoleKDE's terminal, powerful customizationKDE users
AlacrittyGPU-accelerated, very fastPerformance enthusiasts
KittyGPU-accelerated, images in terminalModern features
TerminatorSplit panes, multiple terminalsMulti-tasking

Bash on macOS

macOS comes with Bash pre-installed, but note that since macOS Catalina (2019), the default shell is Zsh.

Install Latest Bash with Homebrew

The built-in Bash on macOS is often outdated (version 3.2). Install the latest:

# Install Homebrew first (if you don't have it)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
 
# Install latest Bash
brew install bash
 
# Add the new Bash to allowed shells
sudo bash -c 'echo /opt/homebrew/bin/bash >> /etc/shells'
 
# Set it as your default shell
chsh -s /opt/homebrew/bin/bash
 
# Verify
bash --version
 
TerminalFeaturesBest For
Terminal.appBuilt-in, reliableQuick use
iTerm2Split panes, search, profiles, hotkey windowPower users (recommended)
AlacrittyGPU-accelerated, fastPerformance
WarpAI-powered, modern UIModern workflow

💡 iTerm2 is highly recommended on macOS

Download it free from iterm2.com. It has features like split panes, search across output, a hotkey window (press a key to show/hide terminal), and much more.

Bash on Windows (WSL)

Windows doesn't have Bash natively, but WSL (Windows Subsystem for Linux) lets you run a full Linux environment inside Windows.

Install WSL

Open PowerShell as Administrator and run:

# Install WSL with Ubuntu (default)
wsl --install
 
# Restart your computer when prompted
 

After restart:

  1. Ubuntu will open automatically and finish setup
  2. Create a username and password when prompted
  3. You now have a full Linux environment with Bash!

Verify Installation

# In your WSL terminal
bash --version
whoami
pwd
 

Install Windows Terminal from the Microsoft Store. It supports:

  • Multiple tabs (PowerShell, CMD, WSL)
  • Split panes
  • Custom themes and fonts
  • GPU-accelerated text rendering

ℹ️ WSL Tips

  • Access Windows files from WSL: cd /mnt/c/Users/YourName
  • Access WSL files from Windows: \\wsl$\Ubuntu\home\username
  • Run Windows programs from WSL: explorer.exe .

Understanding Your Terminal Prompt

When you open your terminal, you'll see something called a prompt. It looks something like this:


username@hostname:~$

Let's break it down:

PartMeaningExample
usernameYour user account namejohn
@Separator@
hostnameYour computer's namelaptop
:Separator:
~Current directory (~ = home)~/Documents
$Regular user prompt$
#Root/superuser prompt#

⚠️ The # prompt means danger!

If you see # instead of $, you're logged in as root (superuser). Be very careful—root can modify or delete anything on the system without confirmation!

Customizing Your Prompt

The prompt is controlled by the PS1 environment variable. Let's customize it!

Basic Prompt Customization

# See your current prompt setting
echo $PS1
 
# Simple prompt with just username and directory
PS1='\u:\w\$ '
 
# Colorful prompt
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 

Prompt Escape Sequences

CodeMeaning
\uUsername
\hHostname (short)
\HHostname (full)
\wCurrent working directory (full path)
\WCurrent directory name only
\dDate (e.g., "Mon Jan 15")
\tTime (24-hour HH:MM:SS)
\TTime (12-hour HH:MM:SS)
\nNewline
\$$ for regular users, # for root
\!History number of current command
\#Command number of current command

Prompt Colors

Colors use ANSI escape codes. Here's a handy reference:

# Color format: \[\033[CODEm\]
# Reset: \[\033[00m\]
 
# Colors:
# 30=Black  31=Red     32=Green   33=Yellow
# 34=Blue   35=Purple  36=Cyan    37=White
# Add 01; prefix for bold: 01;32 = Bold Green
 
# Example: Username in green, directory in blue
PS1='\[\033[01;32m\]\u\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 

A Practical Prompt

Here's a nice, informative prompt:

# Shows: [time] user@host:directory (with colors and newline)
PS1='\[\033[33m\][\t]\[\033[00m\] \[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\n\$ '
 

Essential Configuration Files

Bash reads configuration files when it starts. Understanding these files is crucial:

The Key Files

FileWhen It's ReadPurpose
/etc/profileLogin shellSystem-wide settings for all users
~/.bash_profileLogin shellPersonal settings (runs once at login)
~/.bashrcInteractive non-login shellPersonal settings (runs every new terminal)
~/.bash_logoutOn logoutCleanup commands when you log out
/etc/bash.bashrcInteractive non-loginSystem-wide settings for interactive shells

Login vs Non-Login Shell

  • Login shell: When you log into a system (SSH, TTY, first terminal). Reads ~/.bash_profile
  • Non-login shell: Opening a new terminal tab. Reads ~/.bashrc

💡 Best Practice

Most people put their customizations in ~/.bashrc and then source it from ~/.bash_profile:

# In ~/.bash_profile, add this line:
source ~/.bashrc
 

This way, your customizations work in both login and non-login shells.

A Starter .bashrc File

# ~/.bashrc - Personal Bash configuration
 
# If not running interactively, don't do anything
[[ $- != *i* ]] && return
 
# ============= History Configuration =============
HISTSIZE=10000              # Commands to remember in memory
HISTFILESIZE=20000          # Commands to save to file
HISTCONTROL=ignoreboth      # Ignore duplicates and commands starting with space
HISTTIMEFORMAT="%F %T "     # Add timestamps to history
shopt -s histappend          # Append to history, don't overwrite
 
# ============= Shell Options =============
shopt -s checkwinsize        # Update LINES and COLUMNS after each command
shopt -s cdspell             # Auto-correct minor cd typos
shopt -s dirspell            # Auto-correct directory name typos
shopt -s globstar            # Enable ** for recursive globbing
shopt -s nocaseglob          # Case-insensitive globbing
 
# ============= Prompt =============
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 
# ============= Aliases =============
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias ..='cd ..'
alias ...='cd ../..'
alias grep='grep --color=auto'
alias mkdir='mkdir -pv'
alias df='df -h'
alias du='du -h'
alias free='free -h'
 
# ============= Safety Aliases =============
alias rm='rm -i'             # Ask before deleting
alias cp='cp -i'             # Ask before overwriting
alias mv='mv -i'             # Ask before overwriting
 
# ============= Custom Functions =============
# Create a directory and cd into it
mkcd() {
    mkdir -p "$1" && cd "$1"
}
 
# Extract any archive
extract() {
    if [ -f "$1" ]; then
        case "$1" in
            *.tar.bz2) tar xjf "$1" ;;
            *.tar.gz)  tar xzf "$1" ;;
            *.bz2)     bunzip2 "$1" ;;
            *.rar)     unrar x "$1" ;;
            *.gz)      gunzip "$1" ;;
            *.tar)     tar xf "$1" ;;
            *.tbz2)    tar xjf "$1" ;;
            *.tgz)     tar xzf "$1" ;;
            *.zip)     unzip "$1" ;;
            *.Z)       uncompress "$1" ;;
            *.7z)      7z x "$1" ;;
            *)         echo "'$1' cannot be extracted" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}
 
# ============= PATH =============
# Add local bin directory
export PATH="$HOME/.local/bin:$PATH"
 

Essential Keyboard Shortcuts

Master these keyboard shortcuts to fly through the terminal:

ShortcutAction
Ctrl + AMove cursor to beginning of line
Ctrl + EMove cursor to end of line
Alt + BMove cursor back one word
Alt + FMove cursor forward one word
Ctrl + BMove cursor back one character
Ctrl + FMove cursor forward one character

Editing

ShortcutAction
Ctrl + UDelete from cursor to beginning of line
Ctrl + KDelete from cursor to end of line
Ctrl + WDelete the word before the cursor
Alt + DDelete the word after the cursor
Ctrl + YPaste the last deleted text (yank)
Ctrl + TSwap the last two characters
Alt + TSwap the last two words

History

ShortcutAction
/ Navigate through command history
Ctrl + RReverse search through history
Ctrl + GCancel history search
!!Repeat last command
!$Use last argument of previous command
!*Use all arguments of previous command
!abcRun last command starting with "abc"

Process Control

ShortcutAction
Ctrl + CCancel/kill the current command
Ctrl + ZSuspend the current command (background)
Ctrl + DExit the shell (same as typing exit)
Ctrl + LClear the screen (same as clear)
Ctrl + SFreeze terminal output
Ctrl + QResume terminal output

💡 Ctrl+R is a game-changer

Instead of pressing dozens of times to find a past command, press Ctrl+R and start typing any part of the command. Bash will find the most recent match. Press Ctrl+R again to cycle through older matches. Press Enter to execute or Ctrl+G to cancel.

Getting Help

Bash has built-in help systems. Learn to use them:

# Built-in help for shell commands
help cd
help echo
 
# Manual pages (detailed documentation)
man ls
man bash
 
# Quick usage info
ls --help
grep --help
 
# Search for commands related to a topic
apropos "copy files"
man -k "network"
 
# One-line description of a command
whatis ls
whatis grep
 

Reading Man Pages

Man pages can seem overwhelming. Here's how to navigate them:

KeyAction
Space or fPage forward
bPage backward
/patternSearch forward for "pattern"
?patternSearch backward for "pattern"
nNext search result
NPrevious search result
qQuit
hHelp (show all navigation keys)

Man Page Sections

Man pages are organized into sections:

SectionContent
1User commands
2System calls
3Library functions
4Special files
5File formats
6Games
7Miscellaneous
8System administration
# If a name exists in multiple sections, specify the section:
man 1 printf    # The shell command
man 3 printf    # The C library function
 

🏋️ Exercise 1: Set Up Your Environment

Complete these setup tasks:

Task 1: Open a terminal and verify your Bash version. What version do you have?

💡 Hint
Run bash --version in your terminal.
Show Solution
bash --version
# Example output: GNU bash, version 5.2.15(1)-release
 

Task 2: Check what your current prompt looks like by examining the PS1 variable.

Show Solution
echo $PS1
# This will show the escape codes that define your prompt
 

Task 3: Temporarily change your prompt to show the current time and directory.

💡 Hint
Use \t for time and \w for directory in the PS1 variable.
Show Solution
PS1='[\t] \w\$ '
# This will show something like: [14:30:25] ~/Documents$
# This change is temporary—it will reset when you open a new terminal
 

Task 4: Practice these keyboard shortcuts:

  • Type a long command, then use Ctrl+A to jump to the start
  • Use Ctrl+E to jump to the end
  • Use Ctrl+U to delete the line
  • Press Ctrl+R and search your history
Show Solution

These are hands-on exercises—practice them in your terminal! The shortcuts will become second nature with regular use. Try typing:

echo "This is a very long command to practice keyboard shortcuts"
 

Then practice Ctrl+A, Ctrl+E, Ctrl+K, and Ctrl+U on this line.

🏋️ Exercise 2: Create Your .bashrc

Create or update your ~/.bashrc file with at least:

  • 3 useful aliases
  • A custom prompt with colors
  • History configuration
💡 Hint
Use nano ~/.bashrc or vim ~/.bashrc to edit the file. After saving, run source ~/.bashrc to apply changes without restarting the terminal.
Show Solution
# Open the file for editing
nano ~/.bashrc
 
# Add these lines (at minimum):
 
# History
HISTSIZE=10000
HISTFILESIZE=20000
HISTCONTROL=ignoreboth
 
# Prompt with color
PS1='\[\033[01;32m\]\u\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
 
# Aliases
alias ll='ls -alF'
alias ..='cd ..'
alias cls='clear'
 
# Save and exit (Ctrl+O, Enter, Ctrl+X in nano)
 
# Apply changes
source ~/.bashrc
 
Was this page helpful?
SR

Written by the ShellRAG Team

The ShellRAG editorial team writes practical, beginner-friendly Bash Shell tutorials with tested code examples and real-world use cases. Every article is technically reviewed for accuracy and updated regularly.

Learn more about us →