Setting Up Bash and Your Terminal

Get a current Bash on Linux, macOS or Windows, learn which startup file runs when, and set up your prompt, history, completion, shortcuts and aliases properly.

By The Dark DebuggerUpdated 29 min read

This article gets you a working Bash on Linux, macOS or Windows, then configures it so you can work quickly: prompt, history, tab completion, keyboard shortcuts and aliases. Most of it is about understanding which configuration file Bash reads and when, because that is where most setup problems come from. It follows Introduction to Bash, and the rest of the track assumes the setup described here.

Why your setup matters

Here's a situation almost everyone runs into. You add alias ll='ls -alF' to a config file, and it works. The next day you SSH into the same machine and ll says command not found. Or a PATH change works in your terminal but not in a cron job. Or a script that runs on your laptop fails on a server with an error about $'\r'.

None of these are bugs in Bash. Bash reads different startup files depending on how it was started, and files saved on Windows carry invisible characters that break scripts. Once you know the rules, these problems take a minute to fix instead of an afternoon.

Bash on Linux

Every mainstream Linux distribution ships Bash, and on most of them it's the default login shell. Check what you have:

bash --version
GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Your login shell is stored in the last field of your line in /etc/passwd:

getent passwd sid
sid:x:1000:1000:,,,:/home/sid:/bin/bash

If that field shows something other than /bin/bash and you want Bash, change it with chsh -s /bin/bash and log in again. chsh asks for your password and edits /etc/passwd, so I didn't run it on the test machine, which already used Bash.

Bash on macOS

I couldn't test the steps in this section, because the test lab has no Mac. They are the standard Homebrew procedure.

macOS includes /bin/bash, but it's version 3.2, and since macOS Catalina the default login shell for new accounts is zsh. The introduction explains why. To follow this track on a Mac, install a current Bash with Homebrew:

brew install bash

Homebrew puts it in /opt/homebrew/bin/bash on Apple Silicon Macs and /usr/local/bin/bash on Intel Macs. To make it your login shell, add it to the list of allowed shells and switch:

echo /opt/homebrew/bin/bash | sudo tee -a /etc/shells
chsh -s /opt/homebrew/bin/bash

Three Mac-specific details:

  • Scripts that start with #!/bin/bash still get the old 3.2. Use #!/usr/bin/env bash, which runs the first bash on your PATH.
  • Terminal.app and iTerm2 start a login shell for every new window, so they read ~/.bash_profile rather than ~/.bashrc. The startup-file section below explains how to make both work.
  • Apple's Bash prints a notice that "the default interactive shell is now zsh" each time it starts. export BASH_SILENCE_DEPRECATION_WARNING=1 in ~/.bash_profile turns it off.

If you'd rather stay on zsh, you can still follow along. Type bash to start a Bash session inside your zsh terminal, and exit to return.

Bash on Windows: WSL or Git Bash

Windows has two common ways to run Bash, and they're very different.

WSL (Windows Subsystem for Linux) runs a real Linux distribution, Ubuntu by default, in a lightweight virtual machine. You get the real GNU tools, apt, and exactly the environment a Linux server has. Install it from an administrator PowerShell with wsl --install and restart. (It was already installed on my test machine, so I didn't run the install command.) Microsoft's installation guide covers the details. From PowerShell you can check the version and see which distributions you have:

wsl --version
wsl -l -v
WSL version: 3.0.3.0
Kernel version: 6.18.54.1-1
WSLg version: 1.0.79
[…]
  NAME                   STATE           VERSION
* Ubuntu                 Running         2
  docker-desktop-data    Stopped         2

(Windows PowerShell 5.1 displays this output with extra spaces between letters because wsl.exe writes UTF-16 text. I've removed them above. docker-desktop-data is a distribution that Docker Desktop creates for itself.)

Git Bash comes with Git for Windows. It's Bash compiled for Windows with a small set of Unix tools, enough for Git and simple scripts. On the test machine it reported:

bash --version | head -1
uname -s
GNU bash, version 4.4.23(2)-release (x86_64-pc-msys)
MINGW64_NT-10.0-26300
WSLGit Bash
What it isA full Linux distributionBash plus a few hundred Unix tools, built for Windows
Package managerapt (Ubuntu)None (apt: not found)
Your Windows C: drive/mnt/c/c
Linux-only tools (systemd, cron, /proc, Linux binaries)YesNo
Bash versionWhatever the distribution ships (5.2 on Ubuntu 24.04)Depends on your Git for Windows release
Best forLearning this track, development, anything that will run on a serverGit, quick scripts on Windows files

My recommendation: use WSL for this track. Everything here was tested on Ubuntu under WSL, and what you learn there carries over directly to servers. Keep your projects in the Linux filesystem (~/projects), not under /mnt/c. Access to Windows files from WSL works but is much slower, and Windows tools can leave behind the CRLF line endings described under Common mistakes below.

For a terminal window, Windows Terminal (preinstalled on Windows 11) opens WSL, PowerShell and Git Bash in tabs.

Checking which Bash you're running

bash --version tells you about the bash program found on your PATH. The shell you're typing into reports its own version in two variables:

echo "$BASH_VERSION"
echo "${BASH_VERSINFO[0]}"
5.2.21(1)-release
5

BASH_VERSINFO is an array, and element 0 is the major version. Scripts that need Bash 4 or later (associative arrays, mapfile, ${var,,}) can check it and fail with a clear message instead of a confusing syntax error:

#!/usr/bin/env bash
if (( BASH_VERSINFO[0] < 4 )); then
    echo "This script needs Bash 4 or newer; this is $BASH_VERSION" >&2
    exit 1
fi
declare -A ports=([web]=8080 [api]=9090)
echo "web listens on ${ports[web]}, api on ${ports[api]}"
web listens on 8080, api on 9090

On macOS's Bash 3.2 the same script would stop at the version check, which is the point of it.

Startup files: which file runs when

This is the most useful section of this article. Bash decides which configuration files to read based on two questions:

  • Is the shell interactive? An interactive shell reads commands from you at a prompt. A script, or bash -c 'command', is non-interactive.
  • Is it a login shell? A login shell is the first shell of a session: logging in over SSH, on a text console, or with bash -l. Opening a new terminal tab on a Linux desktop usually starts a non-login interactive shell. macOS terminals start login shells.
ShellTypical way to get oneFiles Bash reads
Interactive loginSSH login, bash -l, a macOS terminal window/etc/profile, then the first one that exists of ~/.bash_profile, ~/.bash_login, ~/.profile. On exit: ~/.bash_logout
Interactive non-loginA new terminal tab on Linux, typing bash/etc/bash.bashrc (on Debian and Ubuntu), then ~/.bashrc
Non-interactiveRunning a script, bash -c '…', cron jobsNone, except the file named in $BASH_ENV if it's set

The phrase "the first one that exists" is where the trouble starts, and you'll see why in a moment.

Proving it with tracer lines

Don't take the table on trust. Make each file announce itself. These commands add an echo line to the top of Ubuntu's default ~/.profile and ~/.bashrc, and to the end of ~/.bash_logout:

sed -i '1i echo ">> reading ~/.profile"' ~/.profile
sed -i '1i echo ">> reading ~/.bashrc"' ~/.bashrc
echo 'echo ">> reading ~/.bash_logout"' >> ~/.bash_logout

A non-interactive shell reads nothing:

bash -c 'echo "hello from a non-interactive shell"'
hello from a non-interactive shell

An interactive non-login shell reads ~/.bashrc only. shopt login_shell confirms what kind of shell it is, and $- contains an i when the shell is interactive:

bash -i
>> reading ~/.bashrc
sid@devbox:~$ echo "$-"
himBHs
sid@devbox:~$ shopt -q login_shell && echo login || echo non-login
non-login
sid@devbox:~$ exit
exit

An interactive login shell reads ~/.profile, which on Ubuntu then reads ~/.bashrc itself. On logout it runs ~/.bash_logout. Ubuntu also prints its login banner here. I've trimmed it:

bash -l
Welcome to Ubuntu 24.04.1 LTS (GNU/Linux 6.18.54.1-microsoft-standard-WSL2 x86_64)
[…]
>> reading ~/.profile
>> reading ~/.bashrc
sid@devbox:~$ shopt -q login_shell && echo login || echo non-login
login
sid@devbox:~$ exit
logout
>> reading ~/.bash_logout

(If the banner annoys you, touch ~/.hushlogin turns it off. The banner itself mentions this.)

The ~/.bashrc line in a login shell comes from this block in Ubuntu's default ~/.profile:

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
	. "$HOME/.bashrc"
    fi
fi

. (also spelled source) runs another file inside the current shell, so everything it defines stays defined. That's how a login shell gets your aliases.

Even a non-interactive login shell enters ~/.bashrc. Ubuntu's ~/.bashrc then stops almost immediately, because of a guard at its top:

bash -l -c 'echo "hello from a non-interactive login shell"'
>> reading ~/.profile
>> reading ~/.bashrc
hello from a non-interactive login shell
# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

Keep that guard. It stops prompt settings and aliases from leaking into scripts and tools that start Bash non-interactively.

The .bash_profile trap

Now the classic mistake. Following some guide, you create a ~/.bash_profile to set your editor:

cat > ~/.bash_profile <<'EOF'
echo ">> reading ~/.bash_profile"
export EDITOR=vim
EOF
bash -l
>> reading ~/.bash_profile
sid@devbox:~$ type ll
bash: type: ll: not found
sid@devbox:~$ echo "$EDITOR"
vim
sid@devbox:~$ exit
logout
>> reading ~/.bash_logout

EDITOR is set, but ll has disappeared. A login shell reads only the first of ~/.bash_profile, ~/.bash_login and ~/.profile that exists. Creating ~/.bash_profile means ~/.profile, and therefore ~/.bashrc, are never read in login shells. Every SSH session has now lost your aliases, prompt and PATH changes.

The fix is to have ~/.bash_profile load ~/.profile explicitly:

cat > ~/.bash_profile <<'EOF'
echo ">> reading ~/.bash_profile"
export EDITOR=vim
# Pull in ~/.profile (which in turn sources ~/.bashrc for interactive shells)
if [ -f ~/.profile ]; then
    . ~/.profile
fi
EOF
bash -l
>> reading ~/.bash_profile
>> reading ~/.profile
>> reading ~/.bashrc
sid@devbox:~$ type ll
ll is aliased to `ls -alF'
sid@devbox:~$ echo "$EDITOR"
vim
sid@devbox:~$ exit
logout
>> reading ~/.bash_logout

When you're done experimenting, remove the tracer lines:

sed -i '/>> reading/d' ~/.profile ~/.bashrc ~/.bash_logout

What goes where

The layout I recommend, which is also what Ubuntu's defaults expect:

  • ~/.profile: environment variables that every program should see (PATH, EDITOR, LANG). It's also read by sh and some display managers, so keep it to POSIX syntax.
  • ~/.bashrc: everything for interactive use: aliases, functions, prompt, history settings, shopt options. Keep the "not interactive, return" guard at the top.
  • ~/.bash_profile: either don't create it, or make it a single line that sources ~/.profile. On macOS, where every terminal window is a login shell, it should source ~/.bashrc.

Two more facts help when debugging:

  • Commands run over SSH (ssh server 'some command') are a special case. From man bash:

    Bash attempts to determine when it is being run with its standard input connected to a network connection,  as
    when  executed  by the historical remote shell daemon, usually rshd, or the secure shell daemon sshd.  If bash
    determines it  is  being  run  non-interactively  in  this  fashion,  it  reads  and  executes  commands  from
    /etc/bash.bashrc  and ~/.bashrc, if these files exist and are readable.

    That's one more reason to keep the interactive guard in ~/.bashrc.

  • Edits to ~/.bashrc don't affect shells that are already running. Reload it with source ~/.bashrc, or open a new terminal.

The prompt: PS1

The text Bash prints before each command comes from the variable PS1. Ubuntu's default looks complicated:

echo "$PS1"
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$

It's built from backslash escapes that Bash replaces each time it draws the prompt. Bash 5 can expand a prompt string on demand with ${var@P}, which is a convenient way to see what each escape produces. Run this from ~/webshop/logs:

for e in '\u' '\h' '\w' '\W' '\t' '\A' '\d' '\$' '\s' '\v' '\j' '\!'; do p=$e; printf '%-4s %s\n' "$e" "${p@P}"; done
\u   sid
\h   devbox
\w   ~/webshop/logs
\W   logs
\t   21:44:20
\A   21:44
\d   Mon Nov 09
\$   $
\s   bash
\v   5.2
\j   0
\!   5

In order: user name, host name, current directory (with ~ for home), its last component only, time with and without seconds, date, $ (or # when you're root), shell name, Bash version, number of background jobs, and this command's history number. Two more are worth knowing: \H is the full host name including the domain, and \n starts a new line for two-line prompts.

Setting PS1 takes effect immediately. Here are a few variations from one session:

PS1='\u@\h:\w\$ '
cd /var/log
PS1='[\t] \W\$ '
cd ~
sid@devbox:~$ cd /var/log
sid@devbox:/var/log$ PS1='[\t] \W\$ '
[21:29:52] log$ cd ~
[21:29:53] ~$

Colours, and why \[ \] matters

Colours are terminal escape sequences such as \e[1;32m (bold green) and \e[0m (reset). Wrap every one of them in \[ and \]:

PS1='\[\e[1;32m\]\u@\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '

\[ \] tell Bash that the characters inside take up no space on screen. Without them Bash miscounts the prompt's width. Long commands then wrap onto the same line, and pressing Up through history leaves garbage on screen. If your prompt ever starts overwriting itself, a missing \[ \] pair is almost always the cause.

Showing the exit status

$? (from the introduction) holds the exit status of the last command. Put it in the prompt with single quotes, so it's evaluated every time the prompt is drawn rather than once when you set it:

PS1='[$?] \u@\h:\w\$ '
false
ls /nonexistent
true
[0] sid@devbox:~$ false
[1] sid@devbox:~$ ls /nonexistent
ls: cannot access '/nonexistent': No such file or directory
[2] sid@devbox:~$ true
[0] sid@devbox:~$

The starter configuration at the end of this article shows the status only when it isn't zero.

Command history

Bash remembers what you type. It keeps the list in memory while the shell runs and writes it to ~/.bash_history when the shell exits. Ubuntu's default ~/.bashrc sets:

grep -n -E 'HIST|histappend' ~/.bashrc
13:HISTCONTROL=ignoreboth
16:shopt -s histappend
18:# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
19:HISTSIZE=1000
20:HISTFILESIZE=2000
SettingWhat it controls
HISTSIZEHow many commands are kept in memory for the current shell
HISTFILESIZEHow many lines ~/.bash_history keeps
HISTCONTROLignorespace skips commands that start with a space, ignoredups skips a command identical to the previous one, ignoreboth does both, and erasedups removes older copies
HISTIGNOREColon-separated patterns never to record, for example ls:ll:history
HISTTIMEFORMATIf set, history shows a timestamp for each entry
shopt -s histappendAppend to the history file on exit instead of overwriting it, so several terminals don't erase each other's history

A thousand commands is a few days of work. I raise both limits a lot (see the starter configuration), because disk space is cheap and a command from three weeks ago is often exactly the one you need.

Here is ignoreboth at work. The duplicated grep is recorded once, and the command that starts with a space (useful when a line contains a password) isn't recorded at all:

cd ~/webshop/logs
tail -n 2 access.log
grep -c '" 50[0-9] ' access.log
grep -c '" 50[0-9] ' access.log
 export DB_PASSWORD='s3cr3t-value'
history 5
    1  cd ~/webshop/logs
    2  tail -n 2 access.log
    3  grep -c '" 50[0-9] ' access.log
    4  history 5

We asked for five entries and got four, because only four commands were recorded.

Re-running commands: !!, !$ and friends

History expansion lets you reuse earlier commands without retyping them. Bash prints the expanded command before running it, so you can see what happened:

ls -l access.log
wc -l !$
!!
!tail
^2^4
sid@devbox:~/webshop/logs$ ls -l access.log
-rw-r--r-- 1 sid sid 221139 Nov  9 21:28 access.log
sid@devbox:~/webshop/logs$ wc -l !$
wc -l access.log
1840 access.log
sid@devbox:~/webshop/logs$ !!
wc -l access.log
1840 access.log
sid@devbox:~/webshop/logs$ !tail
tail -n 2 access.log
[…]
sid@devbox:~/webshop/logs$ ^2^4
tail -n 4 access.log
[…]
ExpansionMeans
!!The whole previous command (the classic is sudo !! after "Permission denied")
!$The last argument of the previous command
!tailThe most recent command that starts with tail
!42Command number 42 from history
^old^newThe previous command with the first old replaced by new

!string runs a command you can't see before it runs. Use it for harmless commands. For anything destructive, search with Ctrl-R instead, so you can check the command before pressing Enter.

Searching history with Ctrl-R

Press Ctrl-R and start typing any part of an earlier command. Bash shows the most recent match as you type:

(reverse-i-search)`tai': tail -n 2 access.log

Press Ctrl-R again to step to older matches, Enter to run the match, the Right arrow to edit it first, or Ctrl-G to cancel. Once you're used to it you'll rarely press Up more than twice.

Tab completion

Press Tab and Bash completes command names, file names, directory names and variable names. With two directories ~/projects/webshop and ~/projects/website, typing cd pro and pressing Tab completes to cd projects/. Typing we and pressing Tab extends it as far as the names agree, cd projects/webs. Pressing Tab twice more lists the choices:

sid@devbox:~$ cd projects/webs
webshop/ website/
sid@devbox:~$ cd projects/webs

Type h, press Tab, and the line becomes cd projects/webshop/. Completion avoids typos as well as saving keystrokes. If Tab doesn't complete, the name you've typed so far doesn't exist, and that is useful to know before you run the command.

Ubuntu's ~/.bashrc also loads the bash-completion package. It teaches Tab about the options and subcommands of individual programs. For example, ls --sor followed by Tab completes to ls --sort.

Keyboard shortcuts

Bash's line editing comes from the readline library, and its default key bindings come from the Emacs editor. These are the ones worth learning first. I checked each of them in a terminal session for this article:

KeysAction
Ctrl-A / Ctrl-EJump to the start / end of the line
Alt-B / Alt-FMove back / forward one word
Ctrl-UDelete from the cursor to the start of the line
Ctrl-KDelete from the cursor to the end of the line
Ctrl-WDelete the word before the cursor
Ctrl-YPaste ("yank") the text you last deleted with Ctrl-U, Ctrl-K or Ctrl-W
Alt-.Insert the last argument of the previous command (press again for older ones)
Ctrl-TSwap the two characters before the cursor (sl becomes ls)
Ctrl-_Undo the last edit
Ctrl-RSearch history backwards
Ctrl-LClear the screen, keeping the current line
Ctrl-CAbandon the current line, or interrupt the running command
Ctrl-DOn an empty line: exit the shell

Ctrl-U and Ctrl-Y together are handy. You're halfway through typing a long command, realise you need to check something first, press Ctrl-U, run the check, then press Ctrl-Y to get the command back. Alt-. saves a lot of typing in sequences like mkdir -p releases/v1.4.2 followed by cd + Alt-. + Enter.

To see what any key does, ask readline:

bind -P | grep -E '^(beginning-of-line|kill-line|unix-word-rubout|yank-last-arg|reverse-search-history) '
beginning-of-line can be found on "\C-a", "\eOH", "\e[1~", "\e[H".
kill-line can be found on "\C-k".
reverse-search-history can be found on "\C-r".
unix-word-rubout can be found on "\C-w".
yank-last-arg can be found on "\e.", "\e_".

\C-a means Ctrl-A, and \e is Escape, which is what Alt sends. On macOS Terminal you have to enable "Use Option as Meta key" in the profile settings for the Alt shortcuts to work. If you know Vim, set -o vi switches to vi-style editing (see the Vim track).

Ctrl-S freezes the terminal

Pressing Ctrl-S by accident makes the terminal stop displaying output. Nothing you type appears, and it looks hung. It isn't. This is old terminal flow control, and Ctrl-Q resumes output (along with anything you typed in the meantime). I confirmed this in a terminal session for this article.

Customising readline with ~/.inputrc

Readline reads ~/.inputrc at startup. This one keeps the system defaults and adds three changes I find worth having:

$include /etc/inputrc
 
# Tab completion ignores case and lists choices on the first Tab
set completion-ignore-case on
set show-all-if-ambiguous on
 
# Up/Down search history for lines starting with what you've typed
"\e[A": history-search-backward
"\e[B": history-search-forward

In a new shell you can check that the settings are active:

bind -v | grep -E 'completion-ignore-case|show-all-if-ambiguous'
set completion-ignore-case on
set show-all-if-ambiguous on

With these settings, cd PRO and Tab completes to cd projects/. Typing tai and pressing Up brings back the last command that started with tai, in my session tail -n 1 access.log, instead of just the previous command.

Aliases, and when to use a function instead

An alias replaces the first word of a command with some text. Ubuntu defines a few:

alias
[…]
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'

Defining your own takes one line, and type shows what a name really runs:

alias weblogs='cd ~/webshop/logs && ls -lh'
weblogs
type weblogs
total 216K
-rw-r--r-- 1 sid sid 216K Nov  9 21:44 access.log
weblogs is aliased to `cd ~/webshop/logs && ls -lh'

To bypass an alias for one command, use command ls or \ls. unalias name removes it. After removing it, Ubuntu's "command not found" helper even suggests packages with similar names:

sid@devbox:~$ unalias weblogs
sid@devbox:~$ weblogs
Command 'weblogs' not found, did you mean:
  command 'weblogo' from deb python3-weblogo (3.7.12-5)
Try: apt install <deb name>

Aliases can't take arguments

An alias is plain text substitution. There's no $1. People try anyway:

alias mkcd='mkdir -p "$1" && cd "$1"'
mkcd reports
mkdir: cannot create directory ‘’: No such file or directory

$1 was empty, so this ran mkdir -p "", and the word reports ended up as an extra argument to cd. Anything that needs arguments should be a function:

unalias mkcd
mkcd() { mkdir -p -- "$1" && cd -- "$1"; }
mkcd reports/2026-11
pwd
/home/sid/reports/2026-11

The rule I follow: an alias for a fixed abbreviation (ll, ..), a function for anything with arguments or logic. Both belong in ~/.bashrc, and neither works inside scripts (see Common mistakes below). Functions are covered properly in Loops, Functions, and Reading Input.

Where you'll use this: a starter configuration

You'll go through this every time you get a new laptop, a fresh WSL install or a new server account. Here is the configuration I'd add to the bottom of Ubuntu's default ~/.bashrc, with everything in this article in one place. Keep Ubuntu's defaults above it: they set up colours, completion and the interactive guard.

First, keep a copy of the original so you can always go back:

cp ~/.bashrc ~/.bashrc.orig

Then open ~/.bashrc in an editor and add at the end:

# ---- Personal settings (added below Ubuntu's defaults) ----
 
# History: big, timestamped, shared between terminals, no noise
HISTSIZE=50000
HISTFILESIZE=100000
HISTCONTROL=ignoreboth:erasedups
HISTIGNORE='ls:ll:history:clear'
HISTTIMEFORMAT='%F %T '
shopt -s histappend
PROMPT_COMMAND='history -a'
 
# Fix small typos in directory names given to cd
shopt -s cdspell
 
# Prompt: show the last exit status when it is not 0
PS1='$(s=$?; ((s)) && printf "[%d] " $s)\[\e[1;32m\]\u@\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
 
export EDITOR=vim
 
# Aliases: short names for commands you type all day
alias ll='ls -alFh'
alias ..='cd ..'
alias ...='cd ../..'
alias weblogs='cd ~/webshop/logs && ls -lt | head'
 
# Functions: for anything that needs arguments
mkcd() { mkdir -p -- "$1" && cd -- "$1"; }

A few of these need explaining. PROMPT_COMMAND runs before each prompt, and history -a appends the latest command to ~/.bash_history straight away, so a second terminal (or a crash) doesn't lose it. cdspell corrects small typos in cd arguments. The prompt runs a tiny $( … ) command that prints the exit status only when it's non-zero.

Check the syntax before you rely on it, then load it into the current shell:

bash -n ~/.bashrc && echo "syntax OK"
source ~/.bashrc
syntax OK

Add the ~/.inputrc from the previous section too. Then, in a new terminal, everything works together:

sid@devbox:~$ type ll mkcd
ll is aliased to `ls -alFh'
mkcd is a function
mkcd ()
{
    mkdir -p -- "$1" && cd -- "$1"
}
sid@devbox:~$ echo "$HISTSIZE $HISTCONTROL"
50000 ignoreboth:erasedups
sid@devbox:~$ false
[1] sid@devbox:~$ ls /no/such/dir
ls: cannot access '/no/such/dir': No such file or directory
[2] sid@devbox:~$ true
sid@devbox:~$ cd ~/webshop/lgos
/home/sid/webshop/logs
sid@devbox:~/webshop/logs$ cd ~
sid@devbox:~$ history 3
    6  2026-11-09 21:44:27 cd ~/webshop/lgos
    7  2026-11-09 21:44:28 cd ~
    8  2026-11-09 21:44:28 history 3

The prompt only shows [1] and [2] after the failing commands, cdspell turned lgos into logs, and history entries have timestamps. If you want these settings on every machine, keep ~/.bashrc, ~/.profile and ~/.inputrc in a Git repository (a "dotfiles" repo) and copy or link them into place on each new machine.

Common mistakes

Your aliases vanish in SSH sessions

Symptom: ll works in a new terminal tab, but command not found over SSH or in bash -l. Cause: a ~/.bash_profile exists that doesn't load ~/.profile or ~/.bashrc, as shown in the .bash_profile trap section above. Fix: make ~/.bash_profile source ~/.profile, or delete it if it does nothing else.

Windows line endings: cannot execute: required file not found

A script written in a Windows editor ends each line with CR LF instead of LF. Bash treats the CR (\r) as part of the line:

./deploy.sh
bash: ./deploy.sh: cannot execute: required file not found

That message is confusing, because deploy.sh is right there. The "required file" is the interpreter from the first line, which is now /bin/bash followed by an invisible \r, and no such program exists. Run it with bash directly and the CR shows up in the next error instead:

bash deploy.sh
deploy.sh: line 2: cd: $'/home/sid/webshop\r': No such file or directory
Deploying from /home/sid

file and cat -A show what's going on. cat -A shows the CR as ^M before the $ that marks the end of each line:

file deploy.sh
cat -A deploy.sh
deploy.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
#!/bin/bash^M$
cd ~/webshop^M$
echo "Deploying from $(pwd)"^M$

Strip the carriage returns, and the script works:

sed -i 's/\r$//' deploy.sh
./deploy.sh
Deploying from /home/sid/webshop

To prevent it, set your editor to use LF line endings for shell scripts. If the scripts live in Git, add a .gitattributes line such as *.sh text eol=lf.

event not found from an exclamation mark

In an interactive shell, ! inside double quotes triggers history expansion:

echo "Hello!world"
echo 'Hello!world'
bash: !world: event not found
Hello!world

Use single quotes for text containing !. A ! at the very end of a string, as in echo "Deploy finished!", is left alone and works. Scripts aren't affected, because history expansion is only active in interactive shells.

Aliases in scripts

cat > check-logs.sh <<'EOF'
#!/bin/bash
ll ~/webshop/logs
EOF
bash check-logs.sh
check-logs.sh: line 2: ll: command not found

Scripts run in a non-interactive shell, which doesn't read ~/.bashrc and doesn't expand aliases. Even defining the alias inside the script fails the same way (line 3: ll: command not found), because alias expansion is switched off in non-interactive shells. Write the full command in scripts, or define a function in the script.

Summary

  • Use a current Bash: 5.x on Linux and WSL, Homebrew's Bash on macOS. Check with echo "$BASH_VERSION", and have scripts that need Bash 4+ test BASH_VERSINFO.
  • On Windows, WSL gives you a real Linux environment. Git Bash is good enough for Git and simple scripts, but it isn't Linux.
  • Login shells read /etc/profile, then the first of ~/.bash_profile, ~/.bash_login and ~/.profile. Interactive non-login shells read ~/.bashrc. Scripts read none of them.
  • Put environment variables in ~/.profile and interactive settings in ~/.bashrc. If ~/.bash_profile exists, it must source ~/.profile (or ~/.bashrc).
  • Prove which files run with tracer echo lines rather than guessing, and reload changes with source ~/.bashrc.
  • In PS1, wrap colour codes in \[ \], and use single quotes so $? is evaluated every time.
  • Increase HISTSIZE and HISTFILESIZE, use ignoreboth, and learn Ctrl-R. !!, !$ and ^old^new save retyping.
  • Aliases are fixed text shortcuts for interactive use. Anything with arguments should be a function, and neither belongs in scripts.

Exercises

Exercise 1: Check for Bash 4 or newereasy

Print your Bash version, then write a single command that prints Bash 4+ features available only if the running shell's major version is at least 4.

Show Solution
echo "$BASH_VERSION"
(( BASH_VERSINFO[0] >= 4 )) && echo "Bash 4+ features available"
5.2.21(1)-release
Bash 4+ features available

(( … )) does arithmetic and returns success when the result is non-zero, and && runs the echo only on success. $BASH_VERSION describes the shell you're in, which is not always the same Bash that bash --version finds on the PATH.

Exercise 2: Trace your startup filesmedium

Add tracer lines to ~/.profile and ~/.bashrc, then find out which files a non-interactive login shell (bash -l -c '…') reads on your system. Explain why ~/.bashrc appears even though the shell isn't interactive. Remove the tracers afterwards.

Show Solution
sed -i '1i echo ">> reading ~/.profile"' ~/.profile
sed -i '1i echo ">> reading ~/.bashrc"' ~/.bashrc
bash -l -c 'echo "hello from a non-interactive login shell"'
>> reading ~/.profile
>> reading ~/.bashrc
hello from a non-interactive login shell

Bash itself only reads ~/.profile here (a login shell, with no ~/.bash_profile present). Ubuntu's ~/.profile then sources ~/.bashrc explicitly whenever it runs under Bash. The tracer at the top of ~/.bashrc fires before the case $- in *i*) guard, which returns straight away because the shell isn't interactive, so no aliases or prompt settings are loaded.

sed -i '/>> reading/d' ~/.profile ~/.bashrc
Exercise 3: Design a compact promptmedium

Build a prompt that looks like [21:37] sid:logs$ : the time as hours and minutes, your user name, and only the last part of the current directory. Check it with ${PS1@P} before you use it.

Show Solution
PS1='[\A] \u:\W\$ '
cd ~/webshop/logs
echo "${PS1@P}"
[21:37] sid:logs$

\A is the 24-hour time without seconds, \u the user and \W the last directory component. ${PS1@P} expands the string exactly as Bash does when it draws the prompt. Add the PS1= line to ~/.bashrc to keep it.

Exercise 4: Keep noise and secrets out of historymedium

Configure the current shell so that history ignores repeated commands, commands that start with a space, and the commands ls, ll, history and clear. Prove it by running ls twice, ll, a command with a leading space, and the same wc command twice, then look at the last three history entries.

Show Solution
HISTCONTROL=ignoreboth
HISTIGNORE='ls:ll:history:clear'
cd ~/webshop
ls
ls
ll
 echo "token=abc123"
wc -l logs/access.log
wc -l logs/access.log
history 3
    3  cd ~/webshop
    4  wc -l logs/access.log
    5  history 3

Entries 1 and 2 are the two settings. The ls and ll lines, the space-prefixed echo and the second wc were never recorded. history 3 itself appears because the history list is updated before the command runs, but because of HISTIGNORE it won't be saved to the file. Note that HISTIGNORE patterns match the whole line, so ls -l would still be recorded. Use 'ls*' to drop every ls command.

Exercise 5: Replace a broken alias with a functionhard

A colleague's ~/.bashrc contains alias bak='cp "$1" "$1.bak"', meant to back up a file before editing it. Show what goes wrong when you run bak nginx.conf, then replace it with a function that copies the file to nginx.conf.YYYY-MM-DD.bak using today's date.

Hint

An alias can't see its arguments. date +%F prints today's date as YYYY-MM-DD.

Show Solution
cd ~/webshop
alias bak='cp "$1" "$1.bak"'
bak nginx.conf
cp: target 'nginx.conf': Not a directory

The alias expanded to cp "" ".bak" nginx.conf. With three arguments, cp treats the last one as a destination directory, and nginx.conf isn't a directory. Replace it with a function:

unalias bak
bak() { cp -- "$1" "$1.$(date +%F).bak"; }
bak nginx.conf
ls
logs  nginx.conf  nginx.conf.2026-11-09.bak

The -- protects against file names that start with a dash, and $(date +%F) inserts the date. Put the function in ~/.bashrc (not the alias) and source it.


Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026, plus Git Bash (Bash 4.4.23) and wsl.exe on the Windows 11 host for the Windows section. The interactive features (prompt, history expansion, Ctrl-R, Tab completion, every shortcut in the table, Ctrl-S/Ctrl-Q) were exercised in a real pseudo-terminal, starting from Ubuntu's default dotfiles in a scratch home directory. The macOS steps, chsh and wsl --install were not run: the lab has no Mac, and the other two would have changed the test machine's account or Windows setup.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.