On this page

Linux Commands

Fundamentals of Computer Science · Unit 3

Linux Commands

Course: Fundamentals of Computer Science Course code: 26CSE0107 Module Type: Complete Linux Command Reference (CHO-aligned) Coverage: 48 essential Linux terminal commands with syntax, examples, key ideas, option flags, and critical distinctions — organized by functional category as per the Chitkara University FCS Semester-1 Course Handout.

Contents

  1. Navigation & directory listing
  2. Directory operations
  3. File creation & manipulation
  4. File inspection & display
  5. Text search & processing
  6. Piping & redirection
  7. Documentation & help systems
  8. Session history
  9. User identification
  10. System information
  11. File permissions & ownership
  12. Process management
  13. Terminal management
  14. Privilege escalation & user switching
  15. System restart
  16. Quick practice sheet
  17. Important command differences

1. Navigation & directory listing

1.1 pwd — Print Working Directory

Purpose: Displays the absolute path of the current working directory.

pwd

Example output:

/home/aadhar

Key idea: Linux directories form a tree beginning at /, called the root directory. If pwd prints /home/aadhar/Documents, you are inside Documents.


1.2 ls — List Directory Contents

Purpose: Displays files and directories.

Usage Command Description
Basic listing ls Lists names of files and directories in current location
Long listing ls -l Shows permissions, links, owner, group, size, timestamp, name
Show hidden files ls -a Includes hidden files (names starting with .)
Combined options ls -la Long listing with hidden files
Human-readable sizes ls -lh Auto-scales sizes to KB, MB, GB
Specific directory ls Documents Lists contents of the named directory
Recursive listing ls -R Lists directory contents recursively including subdirectories
Sort by time ls -lt Long listing sorted by modification time (newest first)
Sort by size ls -lS Long listing sorted by file size (largest first)

Important: In ls -l, the first character helps identify an item: - usually means a regular file and d means a directory.


1.3 cd — Change Directory

Purpose: Changes your current working directory.

Action Command Description
Enter a directory cd Documents Moves into Documents
Parent directory cd .. Moves up one level
Current directory cd . Stays in current directory (no-op)
Home directory cd or cd ~ Jumps to user's home directory
Root directory cd / Jumps to filesystem root
Previous directory cd - Toggles back to previous directory

Key idea: . = current directory, .. = parent directory, ~ = home directory, / = filesystem root.


2. Directory operations

2.1 mkdir — Make Directory

Purpose: Creates one or more directories.

Action Command
Create one directory mkdir college
Create several directories mkdir C Cpp Linux
Create nested directories mkdir -p college/fcs/linux

Important: The -p flag creates missing parent directories automatically. Without -p, creating nested directories where parents don't exist will fail.


2.2 rmdir — Remove Directory

Purpose: Removes an empty directory.

mkdir test
rmdir test

Important: If a directory contains files or subdirectories, plain rmdir normally fails. Use rm -r to recursively remove non-empty directories (with caution).


3. File creation & manipulation

3.1 touch — Create Empty File

Purpose: Creates a new empty file, or updates the access and modification timestamps of an existing file.

touch notes.txt           # creates empty file (or updates timestamps if it exists)
touch file1.txt file2.txt # creates multiple files at once

Key idea: touch does not modify file contents. If the file already exists, only its timestamp metadata is updated.


3.2 echo — Print Text / Write to Files

Purpose: Prints a string to standard output. Combined with redirection, writes text to files.

echo "Hello, Linux!"               # prints to terminal
echo "Name: Rahul" > student.txt    # overwrites file with text
echo "Roll No: 101" >> student.txt  # appends text to file

Critical distinction: > overwrites the file; >> appends to the end.


3.3 cp — Copy Files or Directories

Purpose: Duplicates files or directories.

Action Command Description
Copy a file cp file1.txt file2.txt Creates a duplicate of file1.txt named file2.txt
Copy into a directory cp file.txt /home/user/ Copies file into the target directory
Recursive copy cp -r dir1 dir2 Copies entire directory tree including all contents
Interactive mode cp -i file1.txt file2.txt Prompts before overwriting existing files
Verbose cp -v file1.txt file2.txt Prints what is being copied
cp -r notes backup_notes    # copies entire directory recursively

3.4 mv — Move / Rename Files

Purpose: Moves files/directories to a new location, or renames them if the destination is in the same directory.

mv old.txt new.txt           # renames old.txt to new.txt
mv file.txt /home/user/      # moves file to another directory
mv dir1 dir2                 # renames directory

Key idea: Unlike cp, mv does not leave a copy behind. The original is removed from the source location.


3.5 rm — Remove Files or Directories

Purpose: Deletes files or entire directory trees permanently.

Action Command Description
Delete a file rm file.txt Removes the specified file
Recursive delete rm -r directory/ Deletes directory and all its contents
Force delete rm -f file.txt Deletes without prompting (even if write-protected)
Interactive mode rm -i file.txt Prompts before each deletion
Recursive + force rm -rf directory/ Deletes everything without any prompt

Warning: Linux has no recycle bin for rm. Deleted files are permanently lost. Use rm -rf with extreme caution.


3.6 stat — Detailed File Information

Purpose: Displays comprehensive metadata about a file or directory.

stat student.txt

Example output:

  File: student.txt
  Size: 45              Blocks: 8          IO Block: 4096   regular file
Access: (0644/-rw-r--r--)  Uid: ( 1000/aadhar)   Gid: ( 1000/aadhar)
Access: 2026-09-22 14:30:00.000000000 +0530
Modify: 2026-09-22 14:25:00.000000000 +0530
Change: 2026-09-22 14:25:00.000000000 +0530

Key fields: File size, permissions (octal and symbolic), owner UID/GID, access time, modification time, and change time.


4. File inspection & display

4.1 file — Determine File Type

Purpose: Identifies the type of a file or path.

file notes.txt        # ASCII text
file Documents        # directory
file a.out            # ELF 64-bit LSB executable

Key idea: Linux does not rely only on filename extensions, so file can help identify what an item actually contains (e.g., a .txt file could actually be an image).


4.2 cat — Concatenate and Display Files

Purpose: cat means concatenate. It is used to display files, combine files, and work with redirection.

Action Command Description
Display a file cat hello.txt Prints file contents to terminal
Display multiple files cat file1.txt file2.txt Prints contents of both files sequentially
Create/overwrite a file cat > notes.txt Type text, then press Ctrl+D to save
Append to a file cat >> notes.txt Type text, then press Ctrl+D to append
Combine into another file cat a.txt b.txt > c.txt Concatenates a.txt and b.txt into c.txt
Display with line numbers cat -n notes.txt Prefixes each line with its line number

Critical distinction: > overwrites the destination file; >> appends to the end of the file. This is one of the most commonly tested redirection concepts.


4.3 less — View a File Page by Page

Purpose: Useful for reading long text files interactively without flooding the terminal.

less longfile.txt

Navigation controls inside less:

Key Action
Space Next page
b Previous page
↑ / ↓ Move line by line
/word Search forward for word
n / N Next / previous search match
q Quit viewer

cat vs less: cat prints content directly to terminal (good for short files); less gives an interactive paged view (good for long files).


4.4 more — View a File (Forward Only)

Purpose: Displays file contents one screen at a time, with forward-only scrolling.

more longfile.txt
Key Action
Space Next page
Enter Next line
q Quit viewer

less vs more: less supports backward scrolling and search; more only scrolls forward. less is generally preferred (mnemonic: "less is more").


4.5 head — Display First Lines

Purpose: Displays the first N lines of a file (default: 10 lines).

head notes.txt           # shows first 10 lines
head -n 5 notes.txt      # shows first 5 lines
head -n 20 notes.txt     # shows first 20 lines

4.6 tail — Display Last Lines

Purpose: Displays the last N lines of a file (default: 10 lines).

tail notes.txt           # shows last 10 lines
tail -n 5 notes.txt      # shows last 5 lines
tail -f /var/log/syslog  # follows file in real-time (live monitoring)

Key idea: tail -f is essential for live log monitoring — it continuously prints new lines as they are appended to the file.


5. Text search & processing

5.1 grep — Search Text Patterns

Purpose: Global Regular Expression Print — searches files for lines matching a pattern and prints them.

grep "error" logfile.txt           # find lines containing "error"
grep -i "warning" logfile.txt      # case-insensitive search
grep -n "TODO" code.c              # show line numbers with matches
grep -r "function" /home/user/     # recursive search in directory
grep -c "pass" results.txt         # count matching lines
grep -v "debug" logfile.txt        # invert match (lines NOT containing "debug")
Flag Meaning
-i Case-insensitive search
-n Show line numbers
-r Recursive search through directories
-c Count matching lines only
-v Invert match (exclude matching lines)
-l Show only filenames with matches

5.2 wc — Word Count

Purpose: Counts lines, words, and bytes/characters in files.

wc notes.txt              # lines, words, bytes
wc -l notes.txt           # count lines only
wc -w notes.txt           # count words only
wc -c notes.txt           # count bytes only

Example output:

  12  45  320 notes.txt
# 12 lines, 45 words, 320 bytes

5.3 find — Search for Files

Purpose: Recursively searches the filesystem for files and directories matching specified criteria.

find /home -name "*.txt"            # find all .txt files under /home
find . -name "notes.txt"            # find notes.txt from current directory
find /var -type f -name "*.log"     # find only files (not directories)
find /tmp -type d -name "cache"     # find only directories named "cache"
find . -size +1M                    # find files larger than 1 MB
find . -mtime -7                    # find files modified in last 7 days
Flag Meaning
-name Match by filename (supports wildcards *, ?)
-type f Match regular files only
-type d Match directories only
-size +N Match files larger than N (use k, M, G)
-mtime -N Modified within the last N days

5.4 sort — Sort Lines of Text

Purpose: Sorts lines of a text file or input alphabetically or numerically.

sort names.txt               # alphabetical sort
sort -r names.txt            # reverse alphabetical sort
sort -n numbers.txt          # numerical sort
sort -u names.txt            # sort and remove duplicates
sort -k 2 data.txt           # sort by second column/field
Flag Meaning
-r Reverse order
-n Numerical sort (instead of lexicographic)
-u Unique — remove duplicate lines
-k N Sort by Nth column

6. Piping & redirection

Piping (|) and redirection (>, >>, <) are fundamental concepts for combining commands and controlling input/output flow.

Output Redirection

Operator Meaning Example
> Redirect output to file (overwrites) ls -l > listing.txt
>> Redirect output to file (appends) echo "new line" >> notes.txt
2> Redirect error output to file find / -name "x" 2> errors.txt

Input Redirection

Operator Meaning Example
< Read input from file sort < unsorted.txt

Piping

The pipe operator (|) sends the standard output of one command as input to the next command, creating a processing pipeline.

ls -la | less                      # pipe directory listing into pager
cat file.txt | grep "error"        # search file contents for "error"
cat file.txt | wc -l               # count lines in a file
ps aux | grep "firefox"            # find a running process
history | tail -20                 # show last 20 commands from history
cat names.txt | sort | uniq        # sort and remove duplicates
ls -l | grep ".txt" | wc -l       # count .txt files in current directory

Key idea: Pipes allow you to chain simple commands together to perform complex operations. Each command in the pipeline runs as a separate process.


7. Documentation & help systems

7.1 man — Manual Pages

Purpose: Opens traditional Linux manual pages with comprehensive reference documentation.

man ls
man cat
man mkdir

Navigation: Same as less — Space = next page, b = previous page, /word = search, q = quit.

Use: Use man command when you need syntax, options, and reference documentation for an external command.


7.2 info — Detailed Documentation

Purpose: Provides structured documentation, often with navigable sections and hyperlinks.

info ls
info bash

Difference: man gives traditional manual/reference pages; info may provide more structured, tutorial-style documentation with navigable nodes.


7.3 help — Bash Built-in Help

Purpose: Shows information about Bash built-in commands (commands that are part of the shell itself, not external binaries).

help        # lists all built-in commands
help cd     # detailed help for cd

Important: cd is a shell built-in, so help cd is useful. External programs such as ls are commonly checked with man ls. Use type command to determine whether a command is built-in or external.


7.4 whatis — One-Line Command Description

Purpose: Displays a concise, one-line summary description of a command from its man page.

whatis ls
# ls (1)    - list directory contents

whatis cat
# cat (1)   - concatenate files and print on the standard output

Use: Quick way to check what a command does without opening the full manual.


7.5 whereis — Locate Binary, Source & Manual

Purpose: Finds the binary executable, source code files, and manual page files for a command.

whereis ls
# ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz

whereis cd
# cd:
# (empty because 'cd' is a shell built-in, not an external binary)

Key idea: If whereis returns empty, the command is likely a shell built-in rather than an external executable.


7.6 which — Show Command Path

Purpose: Shows the full path of the shell command executable binary found in $PATH.

which gcc
# /usr/bin/gcc

which python3
# /usr/bin/python3

which vs whereis: which finds only the executable binary in $PATH; whereis additionally locates source and manual page files.


8. Session history

8.1 history — Command History

Purpose: Shows commands previously entered in the shell session.

history

Useful shortcuts:

Shortcut Action
!5 Re-runs command number 5 from history
!! Re-runs the last command
↑ Arrow Retrieves previous commands interactively
history -c Clears the command history

9. User identification

9.1 whoami — Current Username

Purpose: Displays the effective username of the current user.

whoami
# possible output: aadhar

9.2 who — Logged-In Users

Purpose: Shows users currently logged into the system, including their terminal and login time.

who

Difference: whoami = current effective username (single user); who = all currently logged-in users (may show multiple entries).


9.3 id — User and Group Information

Purpose: Displays user ID, group ID, and all group memberships.

id
# uid=1000(aadhar) gid=1000(aadhar) groups=1000(aadhar),27(sudo)

id username    # check another user's identity

Terms: uid = User ID (unique integer identifying a user); gid = primary Group ID.


10. System information

10.1 uname — System Information

Purpose: Displays kernel and system information.

Usage Command Output
Basic uname Linux
All information uname -a Kernel name, hostname, release, version, machine arch
Kernel release uname -r e.g., 5.15.0-91-generic
Machine architecture uname -m e.g., x86_64

10.2 uptime — System Running Time

Purpose: Shows how long the system has been running, plus current time, user count, and load averages.

uptime
# 14:30:05 up  3:45,  2 users,  load average: 0.15, 0.10, 0.05

10.3 free — Memory Information

Purpose: Displays RAM and swap usage.

Usage Command
Basic (bytes) free
Human-readable free -h
Megabytes free -m
Gigabytes free -g

Common columns: total, used, free, shared, buff/cache, available.

Note: available represents the memory that can be allocated to new processes without swapping — it is typically more useful than free for assessing actual availability.


10.4 tty — Terminal Name

Purpose: Displays the terminal device file associated with the current session.

tty
# /dev/pts/0

Note: TTY historically stands for teletypewriter. In modern Linux, /dev/pts/N represents pseudo-terminal slave devices used by terminal emulators and SSH sessions.


10.5 cal — Calendar

Purpose: Displays a calendar.

Usage Command
Current month cal
Full year cal 2026
Specific month/year cal 9 2026

Note: Exact behavior can vary slightly with the installed implementation (ncal vs cal).


10.6 date — Date and Time

Purpose: Displays the current system date and time.

Usage Command
Default format date
Custom formatted date date +"%d-%m-%Y"
Custom formatted time date +"%H:%M:%S"

Common format codes:

Code Meaning Example
%d Day of month (zero-padded) 22
%m Month number 09
%Y Four-digit year 2026
%H Hour (24-hour) 14
%M Minute 30
%S Second 05

10.7 hostname — Computer Hostname

Purpose: Displays the system hostname, identifying the machine on the network.

hostname

Difference: whoami identifies the user; hostname identifies the machine.


11. File permissions & ownership

11.1 chmod — Change File Permissions

Purpose: Changes the read, write, and execute permissions on files and directories.

Octal (numeric) notation:

Each permission has a numeric weight: Read = 4, Write = 2, Execute = 1.

Octal Symbolic Meaning
7 rwx Read + Write + Execute (full control)
6 rw- Read + Write
5 r-x Read + Execute
4 r-- Read only
0 --- No access
chmod 755 script.sh       # Owner: rwx, Group: r-x, Others: r-x
chmod 644 document.txt    # Owner: rw-, Group: r--, Others: r--
chmod 600 private.key     # Owner: rw-, Group: ---, Others: ---

Symbolic notation:

chmod u+x program.bin     # add execute permission for owner (user)
chmod g-w shared.txt      # remove write permission from group
chmod o=r public.txt      # set others permission to read-only
chmod a+r file.txt        # add read permission for all (user + group + others)

Key idea: The three-digit octal number represents permissions for User (Owner), Group, and Others respectively. Example: 754 = Owner rwx, Group r-x, Others r--.


11.2 chown — Change File Owner

Purpose: Changes the owner and/or group of a file or directory.

sudo chown student file.txt            # change owner to 'student'
sudo chown student:cse file.txt        # change owner to 'student', group to 'cse'
sudo chown -R student:cse project/     # recursive ownership change

Note: Changing ownership typically requires sudo (root) privileges.


11.3 chgrp — Change File Group

Purpose: Changes the group ownership of a file or directory.

sudo chgrp cse file.txt               # change group to 'cse'
sudo chgrp -R cse project/            # recursive group change

12. Process management

12.1 ps — Process Status

Purpose: Displays a snapshot of currently active processes.

ps                  # processes in current terminal session
ps aux              # all processes system-wide with detailed info
ps -ef              # full-format listing of all processes

ps aux output columns:

Column Meaning
USER Process owner
PID Process ID
%CPU CPU usage percentage
%MEM Memory usage percentage
COMMAND Command that started the process
ps aux | grep firefox    # find a specific running process

12.2 top — Real-Time Process Monitor

Purpose: Interactive, real-time display of running processes, CPU usage, and memory consumption.

top
Key Action inside top
q Quit
k Kill a process (prompts for PID)
M Sort by memory usage
P Sort by CPU usage
h Help

Note: htop is an enhanced, colorful alternative to top with mouse navigation support (may need to be installed separately).


12.3 kill — Terminate Processes

Purpose: Sends signals to processes, typically to terminate them.

kill 1234              # send SIGTERM (15) — graceful shutdown request
kill -9 1234           # send SIGKILL (9) — immediate forced termination
kill -15 1234          # explicit SIGTERM (same as default)
Signal Number Meaning
SIGTERM 15 Graceful termination (process can clean up)
SIGKILL 9 Immediate forced kill (cannot be caught or ignored)
SIGHUP 1 Hangup — often used to reload configuration

Workflow: Use ps aux | grep name to find the PID, then kill PID to terminate it. Use kill -9 only as a last resort.


13. Terminal management

13.1 clear — Clear Terminal Screen

Purpose: Clears the visible terminal screen, providing a clean workspace.

clear

Shortcut: Ctrl+L is a common terminal shortcut that clears/redraws the screen in most terminal emulators.


14. Privilege escalation & user switching

14.1 su — Switch User

Purpose: Starts a shell as another user, subject to authentication and system configuration.

Action Command
Switch to specific user su username
Switch to root (default) su
Login shell (full environment) su -
Run single command as user su -c "command" username

Important: Authentication depends on the system. su opens a full interactive shell as the target user. su and sudo are not the same.


14.2 sudo — Execute with Elevated Privileges

Purpose: Allows an authorized user to execute a command as another user (commonly root), according to the sudo policy defined in /etc/sudoers.

sudo apt update
sudo mkdir /test
sudo -i                  # interactive root login shell
sudo -u username command # execute as a specific user
sudo -l                  # list allowed privileges

su vs sudo: su switches the entire user shell session; sudo command executes a single permitted command with elevated privileges and returns to the original user.


15. System restart

15.1 reboot — Restart the System

Purpose: Restarts the computer/system.

reboot
sudo reboot

Warning: Do not test this casually unless you actually intend to restart the system. On shared or production servers, always confirm before rebooting.


16. Quick practice sheet

Use this command sequence to test every command covered in these notes:

# === Navigation ===
pwd
ls
ls -l
ls -a
ls -la
ls -lh
cd Documents
cd ..
cd ~
cd /
cd -

# === Directory operations ===
mkdir test
mkdir -p college/fcs/linux
rmdir test

# === File creation & manipulation ===
touch notes.txt
echo "Hello Linux" > notes.txt
echo "Second line" >> notes.txt
cp notes.txt backup.txt
mv backup.txt renamed.txt
stat notes.txt
rm renamed.txt

# === File inspection ===
file notes.txt
cat notes.txt
cat -n notes.txt
cat > notes.txt        # type text, Ctrl+D to save
cat >> notes.txt       # type text, Ctrl+D to append
cat a.txt b.txt > c.txt
less notes.txt
more notes.txt
head notes.txt
head -n 5 notes.txt
tail notes.txt
tail -n 5 notes.txt

# === Text search & processing ===
grep "Hello" notes.txt
grep -i "hello" notes.txt
grep -n "Hello" notes.txt
wc notes.txt
wc -l notes.txt
find . -name "*.txt"
sort names.txt

# === Piping ===
ls -la | less
cat notes.txt | grep "Hello"
cat notes.txt | wc -l
ps aux | grep "bash"
history | tail -10

# === Documentation ===
man ls
info ls
help cd
whatis ls
whereis ls
which gcc

# === History ===
history

# === User identity ===
who
whoami
id

# === System info ===
uname
uname -a
uname -r
uname -m
uptime
free
free -h
tty
cal
date
hostname

# === Permissions ===
chmod 755 script.sh
chmod u+x program.bin
# sudo chown student:cse file.txt
# sudo chgrp cse file.txt

# === Process management ===
ps
ps aux
top
# kill PID

# === Privilege & session ===
su username
sudo command

# === Terminal ===
clear

# === System restart (use with caution!) ===
# reboot

17. Important command differences

Commands Difference
pwd vs ls pwd shows current location (absolute path); ls shows directory contents (files and folders)
cd .. vs cd ~ cd .. moves to the parent directory (one level up); cd ~ jumps to the home directory
. vs .. . refers to the current directory; .. refers to the parent directory
/ vs ~ / is the filesystem root (topmost directory); ~ is the user's home directory (e.g., /home/aadhar)
mkdir vs rmdir mkdir creates a directory; rmdir removes an empty directory
rmdir vs rm -r rmdir removes only empty directories; rm -r recursively removes directories with contents
touch vs cat > touch creates an empty file; cat > creates a file with content from keyboard input
cp vs mv cp duplicates (original remains); mv moves/renames (original is removed)
cat vs less cat prints content directly to terminal; less provides interactive paged viewing
less vs more less supports bidirectional scrolling and search; more only scrolls forward
head vs tail head shows the first N lines; tail shows the last N lines
> vs >> > overwrites/redirects output to a file; >> appends output to the end of a file
who vs whoami who shows all logged-in users; whoami shows the current effective username
hostname vs whoami hostname identifies the machine; whoami identifies the user
su vs sudo su switches the entire user shell; sudo executes a single permitted command as another/elevated user
man vs help man shows manual pages for external commands; help shows documentation for shell built-in commands
man vs info man gives traditional reference pages; info provides more structured/tutorial documentation
which vs whereis which finds only the executable path; whereis also locates source and manual files
whatis vs man whatis gives a one-line summary; man opens the full manual page
chmod vs chown chmod changes permissions (read/write/execute); chown changes ownership (user/group)
ps vs top ps shows a static snapshot of processes; top shows real-time continuous monitoring
kill vs kill -9 kill sends SIGTERM (graceful shutdown); kill -9 sends SIGKILL (immediate forced termination)

Saved Bookmarks

0

Request or Upload Content

Send missing topics, notes, question banks, or corrections directly to Sehjal

Click to upload or drag and drop
PDF, PNG, JPG, DOCX, ZIP (Up to 10MB)

Submitting opens FormSubmit's confirmation or error page. You can return to StudyDump with your browser Back button.