Why learn the terminal?
Ubuntu's graphical interface handles everyday tasks well, but the terminal unlocks capabilities no GUI can match: batch operations on thousands of files, remote server management over SSH, automated backups with cron, scripting repetitive tasks, and precise system troubleshooting. Once comfortable with the command line, you will work faster, automate more, and understand your system at a deeper level.
Getting started
Open a terminal with Ctrl+Alt+T, or search for "Terminal" in the Activities menu. You will see a prompt like:
user@hostname:~$
This tells you your username, the hostname of the machine, the current directory (~ = home), and $ means you are a regular user (# means root). Commands are typed after the prompt and executed by pressing Enter.
Tip: If a command requires administrator privileges, prefix it with sudo (Super User DO). Ubuntu will ask for your password once and cache it for a few minutes.
Navigation
pwd — print working directory
pwd
# /home/user
Shows the absolute path of the directory you are currently in.
ls — list contents
ls # basic list
ls -l # long format: permissions, owner, size, date
ls -la # include hidden files (dot-files)
ls -lh # human-readable sizes (KB, MB, GB)
ls -lt # sort by modification time (newest first)
ls -lS # sort by size (largest first)
Tip: Combine flags freely — ls -lhta shows everything in long, human-readable, time-sorted format including hidden files.
cd — change directory
cd /var/log # go to an absolute path
cd Documents # go to a relative path (inside current dir)
cd ~ # go to home directory
cd .. # go up one level
cd - # go back to previous directory
cd ../.. # go up two levels
Tip: Press Tab to autocomplete directory and file names — this saves keystrokes and prevents typos.
tree — display directory tree
tree # show full tree from current dir
tree -L 2 # limit depth to 2 levels
tree -d # directories only
# install if missing: sudo apt install tree
File and directory management
mkdir — create directories
mkdir projects # create a single directory
mkdir -p a/b/c # create nested directories at once
mkdir dir1 dir2 dir3 # create multiple directories
touch — create files or update timestamps
touch file.txt # create an empty file (or update its timestamp)
touch file1.txt file2.txt # create multiple files
cp — copy
cp file.txt backup.txt # copy a file
cp -r folder/ folder_backup/ # copy a directory recursively
cp -i file.txt dest/ # prompt before overwriting
cp -v file.txt dest/ # verbose: show what is copied
mv — move or rename
mv old.txt new.txt # rename a file
mv file.txt ~/Documents/ # move file to another directory
mv -i src dest # prompt before overwriting
rm — remove
rm file.txt # delete a file (no undo!)
rm -r folder/ # delete a directory and its contents
rm -i file.txt # ask for confirmation first
rm -rf folder/ # force delete — use with extreme caution
Warning: rm is permanent — there is no trash bin. Always double-check paths, especially with -rf. Consider using rm -i by default (see Aliases section).
ln — create links
ln -s /path/to/original link_name # symbolic (soft) link
ln /path/to/original hard_link # hard link
Symbolic links are like shortcuts; hard links share the same data on disk. Prefer symbolic links for most use cases.
Viewing and editing files
cat — display entire file
cat file.txt # print full contents
cat file1.txt file2.txt # concatenate and print both
less and more — page through files
less largefile.log # scroll with arrow keys, q to quit
more largefile.log # similar but simpler
less is preferred — it supports backward scrolling and searching with /pattern.
head and tail — view start or end
head -n 20 file.txt # first 20 lines
tail -n 20 file.txt # last 20 lines
tail -f /var/log/syslog # follow: live updates as new lines appear
tail -f is essential for monitoring log files in real time.
nano — simple text editor
nano file.txt
Edit directly in the terminal. Save with Ctrl+O, exit with Ctrl+X. For more advanced editing, learn vim or install micro.
diff — compare files
diff file1.txt file2.txt # show differences line by line
diff -u file1.txt file2.txt # unified format (like git diffs)
wc — count lines, words, bytes
wc file.txt # lines, words, bytes
wc -l file.txt # lines only
wc -w file.txt # words only
Permissions and ownership
Every file and directory has three permission groups: owner (u), group (g), and others (o). Each group has three permissions: read (r=4), write (w=2), and execute (x=1).
# understanding ls -l output:
# -rwxr-xr-- 1 user group 4096 Mar 01 10:00 script.sh
# ↑↑↑ ↑↑↑ ↑↑↑
# user grp others
# r=read w=write x=execute -=none
chmod — change permissions
chmod 755 script.sh # owner: rwx, group: r-x, others: r-x
chmod 644 file.txt # owner: rw-, group: r--, others: r--
chmod +x script.sh # add execute permission for everyone
chmod u+w file.txt # add write for owner only
chmod go-w file.txt # remove write from group and others
chown — change ownership
sudo chown user:group file.txt # change owner and group
sudo chown -R user:group folder/ # recursive — entire directory tree
sudo chown user file.txt # change owner only
Searching and finding
find — search by name, type, size, date
find . -name "*.log" # find all .log files from current dir
find / -name "nginx.conf" 2>/dev/null # search entire filesystem (suppress errors)
find . -type d -name "backup" # find directories named "backup"
find . -size +100M # files larger than 100 MB
find . -mtime -7 # modified in the last 7 days
find . -name "*.tmp" -delete # find and delete .tmp files
grep — search text inside files
grep "error" logfile.log # lines containing "error"
grep -i "error" logfile.log # case-insensitive
grep -r "TODO" src/ # recursive search in directory
grep -n "function" script.js # show line numbers
grep -c "error" logfile.log # count matching lines
grep -v "debug" logfile.log # invert: lines NOT containing "debug"
which and whereis — locate commands
which python3 # /usr/bin/python3
whereis git # binary, source, and man page locations
locate — fast file search (indexed)
sudo apt install mlocate # install if missing
sudo updatedb # update the index
locate nginx.conf # instant results from index
Pipes and redirection
Pipes (|) send the output of one command as input to another. Redirection (>, >>, <) sends output to files or reads input from them. This is one of the most powerful features of the shell.
Pipes
ls -la | grep ".log" # list files, then filter for .log
cat access.log | sort | uniq -c | sort -rn | head -10
# count unique lines, sort by frequency, show top 10
ps aux | grep nginx # find nginx processes
history | grep "apt install" # search your command history
Redirection
echo "hello" > file.txt # write to file (overwrites!)
echo "world" >> file.txt # append to file
cat file.txt 2> errors.log # redirect errors to a file
cat file.txt > output.txt 2>&1 # redirect both stdout and stderr
wc -l < file.txt # use file as input
tee — write to file AND screen
ls -la | tee listing.txt # display output and save to file
ls -la | tee -a listing.txt # append instead of overwrite
xargs — build commands from input
find . -name "*.tmp" | xargs rm # delete all .tmp files found
cat urls.txt | xargs -I {} curl {} # curl each URL in the file
System information
uname -a # kernel version and architecture
lsb_release -a # Ubuntu version
hostname # machine name
uptime # how long the system has been running
whoami # current username
id # user ID, group ID, groups
date # current date and time
cal # calendar for current month
Hardware info
lscpu # CPU details
free -h # memory usage (human-readable)
df -h # disk space per partition
du -sh folder/ # size of a specific folder
du -sh * | sort -rh | head -10 # top 10 largest items in current dir
lsblk # list block devices (disks, partitions)
lsusb # list USB devices
lspci # list PCI devices (GPU, network card, etc.)
Process management
ps — snapshot of processes
ps aux # all processes, detailed
ps aux | grep nginx # find specific process
ps -ef --forest # tree view of processes
top and htop — live process monitor
top # built-in — press q to quit
htop # improved version (install: sudo apt install htop)
In htop: press F6 to sort, F9 to kill, F5 for tree view.
kill and killall — stop processes
kill 1234 # send SIGTERM to PID 1234 (graceful stop)
kill -9 1234 # send SIGKILL (force stop — last resort)
killall firefox # kill all processes named "firefox"
Background and foreground
long_command & # run in background
jobs # list background jobs
fg %1 # bring job 1 to foreground
# press Ctrl+Z to suspend, then 'bg' to resume in background
nohup — survive logout
nohup ./script.sh & # keeps running after you close the terminal
# output goes to nohup.out by default
Installing and managing software
APT — the package manager
sudo apt update # refresh package index
sudo apt upgrade # upgrade all installed packages
sudo apt full-upgrade # upgrade with dependency changes
sudo apt install package # install a package
sudo apt remove package # remove a package (keep config)
sudo apt purge package # remove package AND config files
sudo apt autoremove # remove unused dependencies
apt search keyword # search for packages
apt show package # show package details
apt list --installed # list all installed packages
Snap packages
snap find keyword # search snap store
sudo snap install app # install a snap
sudo snap remove app # remove a snap
snap list # list installed snaps
Install from .deb file
sudo dpkg -i package.deb # install
sudo apt install -f # fix missing dependencies
Users and groups
sudo adduser newuser # create a new user (interactive)
sudo deluser olduser # delete a user
sudo usermod -aG sudo user # add user to sudo group
groups user # list groups the user belongs to
passwd # change your own password
sudo passwd user # change another user's password
su - user # switch to another user
sudo -i # start a root shell
Networking
IP and interfaces
ip addr # show IP addresses
ip link # show network interfaces
ip route # show routing table
hostname -I # quick: show your IP
Connectivity
ping -c 4 google.com # send 4 pings
traceroute google.com # trace the route to a host
nslookup google.com # DNS lookup
dig google.com # detailed DNS query
curl -I https://example.com # fetch HTTP headers
wget https://example.com/file.zip # download a file
Ports and connections
ss -tulnp # list open ports and listening services
sudo netstat -tulnp # older alternative to ss
sudo lsof -i :80 # what process is using port 80?
Firewall (UFW)
sudo ufw status # check firewall status
sudo ufw enable # enable the firewall
sudo ufw allow 22 # allow SSH
sudo ufw allow 80/tcp # allow HTTP
sudo ufw deny 3000 # block port 3000
sudo ufw delete allow 80/tcp # remove a rule
SSH and remote access
# connect to a remote server
ssh user@192.168.1.100
ssh -p 2222 user@server.com # custom port
# copy files over SSH
scp file.txt user@server:/path/ # local → remote
scp user@server:/path/file.txt . # remote → local
scp -r folder/ user@server:/path/ # copy entire directory
# SSH key setup (passwordless login)
ssh-keygen -t ed25519 # generate key pair
ssh-copy-id user@server # copy public key to server
# now you can login without a password
Compression and archives
# tar (archive)
tar -cf archive.tar folder/ # create archive
tar -czf archive.tar.gz folder/ # create gzip-compressed archive
tar -xzf archive.tar.gz # extract gzip archive
tar -xzf archive.tar.gz -C /dest/ # extract to specific directory
tar -tf archive.tar.gz # list contents without extracting
# zip
zip -r archive.zip folder/ # create zip
unzip archive.zip # extract zip
unzip -l archive.zip # list contents
# gzip (single files)
gzip file.txt # compress → file.txt.gz
gunzip file.txt.gz # decompress
Disk and storage
df -h # disk usage per partition
du -sh /var/log # size of a directory
du -sh * | sort -rh | head # largest items in current dir
lsblk # block devices and mount points
sudo fdisk -l # list all partitions (detailed)
mount # show mounted filesystems
sudo mount /dev/sdb1 /mnt # mount a partition
sudo umount /mnt # unmount
Aliases and .bashrc
Aliases let you create shortcuts for frequently used commands. Add them to ~/.bashrc to make them permanent:
# temporary alias (lost when terminal closes)
alias ll='ls -lah'
alias gs='git status'
# make permanent — add to ~/.bashrc
nano ~/.bashrc
# add these lines at the end:
alias ll='ls -lah'
alias la='ls -A'
alias rm='rm -i' # always ask before deleting
alias update='sudo apt update && sudo apt upgrade -y'
alias myip='curl -s ifconfig.me'
# apply changes without restarting terminal
source ~/.bashrc
Tip: The alias rm='rm -i' adds a safety net — you will be asked to confirm every deletion.
Scheduled tasks (cron)
Cron runs commands automatically at specified intervals. Use crontab -e to edit your schedule:
crontab -e # edit your cron jobs
crontab -l # list your cron jobs
# format: minute hour day month weekday command
# ┌───────── minute (0-59)
# │ ┌─────── hour (0-23)
# │ │ ┌───── day of month (1-31)
# │ │ │ ┌─── month (1-12)
# │ │ │ │ ┌─ day of week (0=Sun, 6=Sat)
# │ │ │ │ │
# * * * * * command
# examples:
0 2 * * * /home/user/backup.sh # every day at 2:00 AM
*/15 * * * * /usr/bin/script.sh # every 15 minutes
0 0 * * 0 sudo apt update # every Sunday at midnight
30 8 1 * * /home/user/monthly-report.sh # 1st of each month at 8:30 AM
Shell scripting basics
A shell script is a text file containing a sequence of commands. Create it, make it executable, and run it:
#!/bin/bash
# backup.sh — simple backup script
SRC="/home/user/Documents"
DEST="/home/user/Backups"
DATE=$(date +%Y-%m-%d)
echo "Starting backup for $DATE..."
mkdir -p "$DEST"
tar -czf "$DEST/backup-$DATE.tar.gz" "$SRC"
echo "Backup complete: $DEST/backup-$DATE.tar.gz"
# make it executable and run
chmod +x backup.sh
./backup.sh
Variables and conditionals
#!/bin/bash
NAME="Ubuntu"
echo "Hello, $NAME!"
# if/else
if [ -f "/etc/os-release" ]; then
echo "File exists"
else
echo "File not found"
fi
# loops
for file in *.log; do
echo "Processing $file"
wc -l "$file"
done
Security essentials
- Keep updated: run
sudo apt update && sudo apt upgraderegularly. - Enable the firewall:
sudo ufw enableand allow only needed ports. - Use SSH keys instead of passwords for remote access.
- Disable root SSH login: set
PermitRootLogin noin/etc/ssh/sshd_config. - Minimize installed software: fewer packages = smaller attack surface.
- Monitor logs: check
/var/log/auth.logfor suspicious login attempts. - Use
fail2banto block IPs after repeated failed login attempts. - Review permissions: never run services as root unless strictly necessary.
Productivity tips
- Tab — autocomplete file and command names.
- Ctrl+R — reverse search through command history.
- Ctrl+C — cancel the current command.
- Ctrl+L — clear the screen (same as
clear). - Ctrl+A / Ctrl+E — jump to start/end of line.
- Ctrl+U — delete from cursor to start of line.
!!— repeat the last command. Very useful:sudo !!(re-run last command as sudo).history— view command history. Re-run with!42(command number 42).man commandorcommand --help— always check the manual first.alias— create shortcuts for long commands you use often.
Frequently asked questions
What is the difference between apt and apt-get?
apt is the newer, user-friendly interface. It combines the most common features of apt-get and apt-cache with progress bars and cleaner output. Use apt for interactive use; apt-get is preferred in scripts for backward compatibility.
When should I use sudo?
Whenever a command needs to modify system files, install software, or change settings that affect all users. If you get "Permission denied," the command likely needs sudo. Never run your entire session as root.
How do I know which directory I am in?
Run pwd. The prompt usually also shows the current directory (the part before $).
Is rm reversible?
No. rm permanently deletes files — there is no trash bin in the terminal. Use rm -i for confirmation, or set an alias. For critical data, maintain backups.
How do I install software not in the apt repositories?
Options include: Snap packages (sudo snap install app), Flatpak, downloading .deb files, adding a third-party PPA, or compiling from source. Prefer Snap or official PPAs for security and automatic updates.
How do I update Ubuntu to a new version?
sudo do-release-upgrade # upgrade to next LTS version
Always back up your data before a version upgrade.
Glossary
- Bash
- Bourne Again Shell — the default shell in most Ubuntu versions. It interprets the commands you type.
- CLI
- Command Line Interface — a text-based way to interact with the operating system, as opposed to a GUI.
- Daemon
- A background process that runs continuously (e.g.,
sshd,nginx,cron). - Flag / Option
- A modifier passed to a command with a dash, like
-lor--verbose, that changes its behavior. - Home directory
- Your personal folder at
/home/username, abbreviated as~. - Package
- A bundled piece of software managed by APT. Packages can be installed, updated, and removed.
- PATH
- An environment variable listing directories where the shell looks for executable commands.
- Pipe
- The
|operator that sends the output of one command as input to another. - PID
- Process ID — a unique number assigned to each running process.
- Root
- The superuser account with unrestricted system access. Use
sudoto run individual commands as root instead of logging in as root. - SSH
- Secure Shell — a protocol for encrypted remote login and command execution.
- Stdin / Stdout / Stderr
- Standard input (keyboard), standard output (screen), and standard error (screen for errors). Redirection changes where these go.
sudo- "Super User DO" — runs a single command with root privileges after password verification.
References and resources
- Ubuntu Documentation — official guides and tutorials.
- GNU Coreutils Manual — reference for standard commands (ls, cp, mv, etc.).
- Advanced Bash-Scripting Guide — in-depth shell scripting reference.
- explainshell.com — paste any command to see what each part does.
- tldr pages — simplified, community-driven man pages with practical examples.
Conclusion
The Ubuntu terminal is a powerful tool that rewards practice. This guide covered navigation, file management, permissions, searching, pipes, system info, processes, software management, users, networking, SSH, compression, disk usage, aliases, scheduled tasks, scripting, and security — everything you need to be productive on the command line.
Start by using the terminal for daily tasks: navigating files, installing software, and checking logs. As these become natural, move on to scripting and automation. The more you use the terminal, the faster and more capable you become.
Action: Open a terminal now with Ctrl+Alt+T and try five commands from this guide — muscle memory starts with repetition.