Bash Cheatsheet

Complete Bash cheatsheet covering shortcuts, file operations, variables, functions, flow controls, I/O redirection, and process handling for shell scripting.

Bash Cheatsheet

Bash

Shell

Terminal

Scripting

Complete reference for Bash shell commands, shortcuts, scripting techniques, and advanced terminal operations for efficient command-line usage.

Quick Reference

⌨️ Shortcuts & History

Essential keyboard shortcuts and command history

📁 File Operations

File and directory management commands

🔧 Variables & Functions

Shell scripting and variable manipulation

🔄 Process Control

Job management and process handling

Shortcuts and History

Master these keyboard shortcuts to dramatically improve your command-line efficiency and navigation speed.

Move to beginning of line

CTRL+A

Move to end of line

CTRL+E

Move backward one character

CTRL+B

Move forward one character

CTRL+F

Move backward one word

ALT+B

Move forward one word

ALT+F

Editing Shortcuts

Delete to end of line

CTRL+K

Delete to beginning of line

CTRL+U

Delete word behind cursor

CTRL+W

Delete next word

ALT+D

Transpose two characters

CTRL+T

Transpose two words

ALT+T

Control Shortcuts

Halt current command

CTRL+C

Log out or delete character

CTRL+D

Clear screen

CTRL+L

Suspend current command

CTRL+Z

History Navigation

Previous command in history

CTRL+P

Next command in history

CTRL+N

Search backward in history

CTRL+R

Repeat last command

!!

Refer to command line 'n'

!<n>

Refer to command starting with 'string'

!<string>

Show command history

history

Advanced Shortcuts

Capitalize word from cursor

ALT+C

Lowercase word from cursor

ALT+L

Uppercase word from cursor

ALT+U

Paste last word from previous command

ALT+.

Start recording keyboard macro

CTRL+X then (

Stop recording keyboard macro

CTRL+X then )

Execute recorded macro

CTRL+X then E

Bash Basics

Environment Information

Display all environment variables

env

Show current shell

echo $SHELL

Show Bash version

echo $BASH_VERSION

Switch to Bash shell

bash

Find Bash location

whereis bash

Find Bash executable path

which bash

Clear terminal screen

clear

Exit current session

exit

File Commands

File operations are fundamental to shell usage. These commands help you navigate, manipulate, and manage files efficiently.

File Listing and Information

List files in current directory

ls

List files with detailed information

ls -l

List all files including hidden

ls -a

Show directory tree structure

tree

Show file/directory sizes

du <filename>

Show disk usage

df

File Creation and Modification

Create or update file

touch <filename>

Create temporary file

mktemp -t <filename>
ln -s <filename> <link>
readlink <filename>

File Content Operations

Display file content

cat <filename>

Display file with line numbers

cat -n <filename>

Show line numbers in file

nl <file.sh>

Copy file content to another file

cat filename1 > filename2

Append file content to another file

cat filename1 >> filename2

Show first part of file

more <filename>

Show first lines of file (default: 10)

head <filename>

Show last lines of file (default: 10)

tail <filename>

Follow file changes in real-time

tail -f <filename>

File Management

Move/rename file

mv <filename1> <dest>

Copy file

cp <filename1> <dest>

Remove file

rm <filename>

Edit file with Vim

vim <filename>

File Search and Analysis

Find files by name

find . -name <name> <type>

Compare two files

diff <filename1> <filename2>

Count lines, words, characters

wc <filename>

Count only lines

wc -l <filename>

Count only words

wc -w <filename>

Count only characters

wc -c <filename>

Sort file contents alphabetically

sort <filename>

Sort numerically

sort -n <filename>

Sort in reverse order

sort -r <filename>

Sort by specific field

sort -t -k <filename>

Reverse string characters

rev

File Permissions and Compression

Change file permissions

chmod -options <filename>

Compress file with gzip

gzip <filename>

Decompress gzip file

gunzip <filename>

View gzipped file without decompressing

gzcat <filename>

Text Processing

Search for pattern in files

grep <pattern> <filenames>

Search recursively in directory

grep -r <pattern> <dir>
head -n file_name | tail +n

Display lines from x to y

head -y lines.txt | tail +x

Replace pattern in file (output to stdout)

sed 's/<pattern>/<replacement>/g' <filename>

Replace pattern in file (in-place)

sed -i 's/<pattern>/<replacement>/g' <filename>

Replace pattern from input stream

echo "this" | sed 's/is/at/g'

Printing Operations

lpr <filename>

Check printer queue

lpq

Remove job from printer queue

lprm <jobnumber>

Convert text to PostScript

genscript
dvips <filename>

Directory Commands

Basic Directory Operations

Create new directory

mkdir <dirname>

Remove empty directory

rmdir <dirname>

Remove directory and contents

rmdir -rf <dirname>

Rename directory

mv <dir1> <dir2>

Copy directory recursively

cp -r <dir1> <dir2>

Directory Navigation

Change to home directory

cd

Change to parent directory

cd ..

Change to specific directory

cd <dirname>

Change to home directory

cd ~

Change to previous directory

cd -

Show current directory

pwd

SSH, System Info & Network Commands

System information and network commands are essential for server management and troubleshooting.

SSH Operations

Connect to host as user

ssh user@host

Connect on specific port

ssh -p <port> user@host

Copy SSH key to host

ssh-copy-id user@host

User and System Information

Show current username

whoami

Switch to different user

su <user>

Switch to root user

su -

Execute command as root

sudo <command>

Change password

passwd

Show disk quota

quota -v

Show current date and time

date

Show month's calendar

cal

Show system uptime

uptime

Show who's online

w

Show user information

finger <user>

Show kernel information

uname -a

Show command manual

man <command>

Show command documentation

info <command>

Show built-in help

help

Show last logins

last <yourUsername>

Process Management

List your processes

ps -u yourusername

Kill process by PID

kill <PID>

Kill all processes by name

killall <processname>

Show active processes

top

List open files

lsof

List background jobs

bg

Bring job to foreground

fg

Bring specific job to foreground

fg <job>

Network Commands

Ping host

ping <host>

Get domain whois information

whois <domain>

Get DNS information

dig <domain>

Reverse DNS lookup

dig -x <host>

Download file

wget <file>

Show network connections

netstat

Measure command execution time

time <command>

Variables

Variables in Bash are fundamental for storing data and creating dynamic scripts.

Basic Variable Operations

Define a variable

varname=value

Define variable for subprocess

varname=value command

Check variable value

echo $varname
echo $$
echo $!

Display exit status of last command

echo $?

Read input into variable

read <varname>

Read input with prompt

read -p "prompt" <varname>

Display in columns

column -t <filename>

Perform mathematical calculation

let <varname> = <equation>

Environment Variables

Export environment variable

export VARNAME=value

Export function

export -f <funcname>

Export and assign simultaneously

export var1="var1 value"

Copy Bash variable

export <varname>

Declare exported variable

declare -x <varname>

Arrays

Define array elements

array[0]=valA
array[1]=valB
array[2]=valC

Alternative array definition

array=([2]=valC [0]=valA [1]=valB)

Another array definition method

array=(valA valB valC)

Access array element

${array[i]}

Get length of array element

${#array[i]}

Get number of array elements

${#array[@]}

Variable Declarations

Treat variables as arrays

declare -a

Use function names only

declare -f

Display function names without definitions

declare -F

Treat variables as integers

declare -i

Make variables read-only

declare -r

Mark variables for export

declare -x

Convert to lowercase

declare -l

Make associative array

declare -A

Parameter Expansion

Return value or default word

${varname:-word}

Return value or word (alternative)

${varname:word}

Set variable if null and return

${varname:=word}

Return value or print error

${varname:?message}

Return word if variable exists

${varname:+word}

Extract substring

${varname:offset:length}

Remove shortest match from beginning

${variable#pattern}

Remove longest match from beginning

${variable##pattern}

Remove shortest match from end

${variable%pattern}

Remove longest match from end

${variable%%pattern}

Replace first match

${variable/pattern/string}

Replace all matches

${variable//pattern/string}

Get variable length

${#varname}

Pattern Matching

Match zero or more occurrences

*(patternlist)

Match one or more occurrences

+(patternlist)

Match zero or one occurrence

?(patternlist)

Match exactly one pattern

@(patternlist)

Match anything except pattern

!(patternlist)

Command Substitution

Run command and return output

$(UNIX command)

Make variable local

typeset -l <x>

Functions

Functions allow you to group commands and create reusable code blocks in your scripts.

Function Definition

Define a function

function functname() {
  shell commands
}

Delete function definition

unset -f functname

Display all defined functions

declare -f

Flow Controls

Flow control structures allow you to create conditional logic and loops in your scripts.

Logical Operators

AND operator

statement1 && statement2

OR operator

statement1 || statement2

AND operator in test

-a

OR operator in test

-o

String Comparisons

String equality

str1 == str2

String inequality

str1 != str2

String less than (alphabetically)

str1 < str2

String greater than (alphabetically)

str1 > str2

String sorted after

str1 \> str2

String sorted before

str1 \< str2

String is not null

-n str1

String is null

-z str1

File Tests

File exists

-a file

File is directory

-d file

File exists (same as -a)

-e file

File is regular file

-f file

File is readable

-r file

File exists and not empty

-s file

File is writable

-w file

File is executable

-x file

File was modified since last read

-N file

You own the file

-O file

File group matches yours

-G file

File1 is newer than file2

file1 -nt file2

File1 is older than file2

file1 -ot file2

Numeric Comparisons

Less than

-lt

Less than or equal

-le

Equal

-eq

Greater than or equal

-ge

Greater than

-gt

Not equal

-ne

Conditional Statements

If statement

if condition
then
  statements
[elif condition
  then statements...]
[else
  statements]
fi

Case statement

case expression in
  pattern1 )
    statements ;;
  pattern2 )
    statements ;;
esac

Loops

For loop with range

for x in {1..10}
do
  statements
done

For loop with list

for name [in list]
do
  statements that can use $name
done

C-style for loop

for (( initialisation ; ending condition ; update ))
do
  statements...
done

Select menu

select name [in list]
do
  statements that can use $name
done

While loop

while condition; do
  statements
done

Until loop

until condition; do
  statements
done

Command-Line Processing

Command Lookup Override

Remove alias and function lookup

command

Look up only built-ins

builtin

Enable/disable shell built-ins

enable

Re-evaluate arguments

eval

Input/Output Redirectors

I/O redirection is powerful for controlling where command input comes from and where output goes.

Basic Redirection

Pipe output to input

cmd1|cmd2

Input from file

< file

Output to file

> file

Append to file

>> file

Force output to file

>|file

Use file for both input and output

<> file

File Descriptor Operations

Force output from descriptor n

n>|file

Use file for both I/O on descriptor n

n<>file

Direct descriptor n to file

n>file

Take descriptor n from file

n<file

Append descriptor n to file

n>>file

Duplicate stdout to descriptor n

n>&

Duplicate stdin from descriptor n

n<&

Copy output descriptor

n>&m

Copy input descriptor

n<&m

Direct stdout and stderr to file

&>file

Close standard input

<&-

Close standard output

>&-

Close output from descriptor n

n>&-

Close input from descriptor n

n<&-

Output to terminal and file

|tee <file>

Process Handling

Process management is crucial for controlling running programs and managing system resources.

Background Jobs

Run job in background

myCommand &

List all jobs

jobs

List jobs with PIDs

jobs -l

Bring job to foreground

fg

Bring most recent background job

fg %+

Bring second most recent job

fg %-

Bring job number N

fg %N

Bring job starting with string

fg %string

Bring job containing string

fg %?string

Process Termination

List all signals

kill -l

Terminate process by PID

kill PID

Send specific signal

kill -s SIGKILL 4500

Send TERM signal

kill -15 913

Kill job by number

kill %1

Process Information

Show current processes

ps

Show all processes with tty

ps -a

Signal Handling

Execute command on signal

trap cmd sig1 sig2

Ignore signals

trap "" sig1 sig2

Reset signal handling

trap - sig1 sig2

Process Control

Remove process from job list

disown <PID|JID>

Wait for background jobs

wait

Wait specified seconds

sleep <number>

Display progress bar

pv

Auto-respond yes

yes

Debugging Shell Programs

Debugging tools help you identify and fix issues in your shell scripts.

Syntax Checking

Check syntax without running

bash -n scriptname

Set no-execute option in script

set -o noexec

Verbose Output

Echo commands before running

bash -v scriptname

Set verbose option in script

set -o verbose

Execution Tracing

Echo commands after processing

bash -x scriptname

Set trace option in script

set -o xtrace

Debug Traps

trap 'echo $varname' EXIT

Error trap function

function errtrap {
  es=$?
  echo "ERROR line $1: Command exited with status $es."
}
 
trap 'errtrap $LINENO' ERR

Debug trap function

function dbgtrap {
  echo "badvar is $badvar"
}
 
trap dbgtrap DEBUG

Turn off debug trap

trap - DEBUG

Return trap function

function returntrap {
  echo "A return occurred"
}
 
trap returntrap RETURN

Colors and Backgrounds

Color codes allow you to add visual formatting to your terminal output and scripts.

Reset Color

Text reset

Color_Off='\033[0m'

Regular Colors

Basic colors

Black='\033[0;30m'    # Black
Red='\033[0;31m'      # Red
Green='\033[0;32m'    # Green
Yellow='\033[0;33m'   # Yellow
Blue='\033[0;34m'     # Blue
Purple='\033[0;35m'   # Purple
Cyan='\033[0;36m'     # Cyan
White='\033[0;97m'    # White

Additional colors

LGrey='\033[0;37m'    # Light Gray
DGrey='\033[0;90m'    # Dark Gray
LRed='\033[0;91m'     # Light Red
LGreen='\033[0;92m'   # Light Green
LYellow='\033[0;93m'  # Light Yellow
LBlue='\033[0;94m'    # Light Blue
LPurple='\033[0;95m'  # Light Purple
LCyan='\033[0;96m'    # Light Cyan

Bold Colors

Bold text colors

BBlack='\033[1;30m'   # Bold Black
BRed='\033[1;31m'     # Bold Red
BGreen='\033[1;32m'   # Bold Green
BYellow='\033[1;33m'  # Bold Yellow
BBlue='\033[1;34m'    # Bold Blue
BPurple='\033[1;35m'  # Bold Purple
BCyan='\033[1;36m'    # Bold Cyan
BWhite='\033[1;37m'   # Bold White

Underlined Colors

Underlined text colors

UBlack='\033[4;30m'   # Underlined Black
URed='\033[4;31m'     # Underlined Red
UGreen='\033[4;32m'   # Underlined Green
UYellow='\033[4;33m'  # Underlined Yellow
UBlue='\033[4;34m'    # Underlined Blue
UPurple='\033[4;35m'  # Underlined Purple
UCyan='\033[4;36m'    # Underlined Cyan
UWhite='\033[4;37m'   # Underlined White

Background Colors

Background colors

On_Black='\033[40m'   # Black background
On_Red='\033[41m'     # Red background
On_Green='\033[42m'   # Green background
On_Yellow='\033[43m'  # Yellow background
On_Blue='\033[44m'    # Blue background
On_Purple='\033[45m'  # Purple background
On_Cyan='\033[46m'    # Cyan background
On_White='\033[47m'   # White background

Usage Examples

echo -e "${Green}This is GREEN text${Color_Off} and normal text"
echo -e "${Red}${On_White}This is Red text on White background${Color_Off}"

Printf with colors

printf "${Red} This is red \n"

Tips & Tricks

These advanced tips will help you become more productive with Bash and shell scripting.

Aliases

Set an alias in .bash_profile

cd; nano .bash_profile
# Add your alias
alias gentlenode='ssh admin@gentlenode.com -p 3404'

Quick Directory Access

Set up cdable variables in .bashrc

cd; nano .bashrc
# Add these lines
shopt -s cdable_vars
export websites="/Users/mac/Documents/websites"
 
# Then source and use
source .bashrc
cd $websites

Best Practices

Follow these Bash best practices for writing maintainable and efficient shell scripts.

  • Use proper quoting to handle spaces and special characters in variables
  • Check exit codes using $? to handle errors appropriately
  • Use functions to organize code and avoid repetition
  • Add error handling with set -e to exit on errors
  • Use meaningful variable names and add comments for clarity
  • Test scripts thoroughly before deploying to production
  • Use shellcheck to validate script syntax and catch common issues
  • Handle edge cases like empty inputs and missing files

Learn More

Explore comprehensive Bash documentation and advanced scripting techniques

Written by

Deepak Jangra

Created At

Wed Jan 15 2025

Updated At

Fri Jun 13 2025

Cheatsheets

Your go-to resource for quick reference guides on essential development tools and technologies.

© 2025 Deepak Jangra. All rights reserved.