Lab 123
Lab 123
Guide
A Reference for Essential Operations
AI Generated Resource
Contents
2
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
1 pwd
2
Description: This command is fundamental for orienting yourself within the file system
hierarchy. The output is the absolute path from the root directory (/).
Common Options:
• -l: Long listing format (shows permissions, links, owner, group, size, modification date,
name).
• -a, –all: Shows all files, including hidden files (those starting with a dot .).
• -A, –almost-all: Shows hidden files, but not . (current directory) and .. (parent directory).
• -h, –human-readable: With -l, prints sizes in a human-readable format (e.g., 1K, 234M,
2G).
3
Comprehensive Linux Command Guide May 22, 2025
• -d, –directory: Lists directories themselves, rather than their contents. Useful with -l to
see details of a directory.
• -F, –classify: Appends a character to entries indicating their type (e.g., / for directory, *
for executable).
Common Usage:
• man -k <keyword>: Searches the short descriptions and manual page names for the keyword.
(Equivalent to apropos <keyword>)
• man <section_number> <name>: Displays a specific section of a manual page. Example: man
5 passwd for the password file format.
• Scroll: Use Arrow keys, Page Up/Down, Spacebar (down one page).
• Search: Type / followed by the search term, then press Enter. Use n for the next match and
N for the previous match.
• Quit: Press q.
4
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
1 clear
2
Common Usage:
• mkdir new_directory_name
Common Options:
• -p, –parents: Create parent directories as needed. No error if they already exist. This is
essential for creating nested directory structures in one go.
• -m MODE, –mode=MODE: Set file mode (permissions) for the new directories, similar to chmod.
Common Usage:
• touch filename.txt
Description: Useful for quickly creating placeholder files or for managing timestamps, which
can be important for build systems or scripts that rely on file modification times.
5
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
• rm -rf directory_name (forcefully removes a directory and its contents without prompting;
-f for force, -r for recursive)
Common Options:
• -r, -R, –recursive: Remove directories and their contents recursively. This is necessary
when deleting a directory that is not empty.
• -f, –force: Override most prompts and ignore non-existent files. Use with caution.
• -i: Prompt before every removal, offering a safer way to delete files.
Common Usage:
• rmdir empty_directory_name
Common Options:
• -p, –parents: Remove the specified directory and its parent directories if they also become
empty after the child is removed. For example, rmdir -p a/b/c would attempt to remove c,
then b, then a.
Common Usage:
6
Comprehensive Linux Command Guide May 22, 2025
• cp source_file destination_file
• cp source_file destination_directory/
Common Options:
• -r, -R, –recursive: Copy directories recursively. Essential for copying entire directory
structures.
• -p: Preserves file attributes such as mode (permissions), ownership, and timestamps.
• -a, –archive: Equivalent to -dR –preserve=all. Useful for making backups as it preserves
almost everything.
• If copying a single file to an existing file name, the destination file is typically overwritten
(unless -i or -n for no-clobber is used).
Common Usage:
7
Comprehensive Linux Command Guide May 22, 2025
• mv ../../report.tex . (moves report.tex from two levels up into the current directory
.)
Common Options:
• -i, –interactive: Prompt before overwriting an existing file at the destination.
• -n, –no-clobber: Do not overwrite an existing file. If a file with the same name exists at the
destination, the move for that specific file is skipped.
Common Usage:
• cat filename.txt (displays the content of filename.txt)
• cat > newfile.txt (allows typing text directly, which is then saved to newfile.txt upon
pressing Ctrl+D)
8
Comprehensive Linux Command Guide May 22, 2025
• -A, –show-all: Equivalent to -vET (shows non-printing characters, tabs as Î, and line endings
as $).
Common Usage:
Common Options:
• -n <number>, –lines=<number>: Print the first <number> lines instead of the default 10.
• -c <bytes>, –bytes=<bytes>: Print the first <bytes> bytes. Suffixes like ’k’, ’m’ can be
used.
• Save the 25 first lines to another file: head -n 25 numtext.txt > first25lines.txt
Common Usage:
• tail -f filename.log (outputs appended data as the file grows; useful for monitoring log
files in real-time)
Common Options:
• -n <number>, –lines=<number>: Print the last <number> lines instead of the default 10. If
number is preceded by ’+’, print lines starting with that line number from the start of the
file.
9
Comprehensive Linux Command Guide May 22, 2025
• -f, –follow[={name|descriptor}]: Output appended data as the file grows. This is very
useful for monitoring log files.
Common Usage:
• less filename.txt
Interactive Commands (while less is running):
• Space bar or f or Ctrl+F: Scroll forward one screen.
• /<pattern>: Search forward for pattern. Press n for next match, N for previous.
• ?<pattern>: Search backward for pattern. Press n for next match (in reverse direction), N
for previous.
• q: Quit less.
Common Options (when launching less):
• -N: Display line numbers at the beginning of each line.
• -S: Chop long lines (lines wider than the screen will not be wrapped). Useful for viewing wide
log files. You can scroll horizontally with arrow keys.
• -i: Ignore case in searches, unless the pattern contains uppercase letters.
• -M: More verbose prompt, showing line numbers and percentage through the file.
10
Comprehensive Linux Command Guide May 22, 2025
Modes of Operation:
• Command Mode (Normal Mode): Default mode. Keystrokes are interpreted as com-
mands (navigation, deletion, copying, etc.). Press Esc from other modes to return here.
• Insert Mode: For typing text directly into the file. Entered from Command Mode using
commands like i, a, o, etc.
• Ex Mode (Last Line Mode): For saving, quitting, searching, replacing, and running other
extended commands. Entered from Command Mode by typing :.
Basic Operations:
• Saving and Quitting (Ex Mode commands, type : first from Command Mode):
11
Comprehensive Linux Command Guide May 22, 2025
• Deleting:
– yy or Y: Yank (copy) the current line. (Prefix with number for multiple lines, e.g., 3yy).
12
Comprehensive Linux Command Guide May 22, 2025
• Undo/Redo:
• Change Case:
– ~: Toggle case of the character under the cursor and move to the next character.
• Searching:
• range:
∗ %: Whole file (e.g., :%s/...).
∗ N,M: Lines N through M (e.g., :10,20s/...).
∗ .: Current line.
∗ $: Last line.
• flags:
∗ g (global): Replace all occurrences on a line (without g, only the first occurrence on
each line in range is replaced).
∗ c (confirm): Prompt before each replacement.
∗ i (ignore case): Make the search case-insensitive.
• Example: :%s/old_text/new_text/gc (replace all occurrences of "old_text" with "new_text"
in the entire file, with confirmation for each).
Repeating Commands: Many commands in Command Mode can be prefixed with a number
to repeat them. For example, 3dd deletes 3 lines, 5yy yanks 5 lines, 10j moves down 10 lines.
13
Comprehensive Linux Command Guide May 22, 2025
Interface: The main area is for text editing. Common command shortcuts are displayed at the
bottom of the screen. ˆ (caret) denotes the Ctrl key. M- (meta) denotes the Alt key.
Basic Operations and Common Shortcuts:
• Navigation: Use Arrow Keys, Page Up/Down, Home, End.
– Ctrl+A or Home: Go to the beginning of the current line.
– Ctrl+E or End: Go to the end of the current line.
– Ctrl+Y or PageUp: Move up one page.
– Ctrl+V or PageDown: Move down one page.
– Alt+G or Ctrl+_ (then enter line number): Go to a specific line number.
• Editing: Type directly. Use Backspace or Delete to remove text.
• Saving:
– Ctrl+O (WriteOut): Save the current file. Prompts for a filename if untitled, or confirms
the current filename. Press Enter to confirm.
• Exiting:
– Ctrl+X (Exit): Exits nano. If the file has unsaved changes, it will prompt to save them
(Yes/No/Cancel).
• Cutting, Copying, and Pasting:
– Marking Text: Alt+A or Ctrl+ˆ (Set Mark). Move cursor to select text.
– Cut: Ctrl+K (Cut Text). Cuts the selected text or the current line if no text is selected.
– Copy: Alt+ˆ or Alt+6 (Copy Text). Copies the selected text or the current line.
– Paste: Ctrl+U (Uncut Text). Pastes the text from the cut/copy buffer.
• Searching:
– Ctrl+W (Where Is / Find): Prompts for a search term. Press Enter to search.
– Alt+W (Find Next): Find the next occurrence of the last search term.
• Search and Replace:
– Ctrl+\ (Replace), or Alt+R on some systems. Prompts for the search term, then the
replacement term. Options to replace this instance, all instances, or skip.
• Undo/Redo:
– Alt+U: Undo the last action.
– Alt+E: Redo the last undone action.
• Help:
– Ctrl+G (Get Help): Displays the nano help screen with a list of commands. Press Ctrl+X
to exit help.
Installing nano (if not present on the system): Typically installed using the system’s
package manager. For Debian-based systems (like Ubuntu, Mint):
1 sudo apt update
2 sudo apt install nano
3
14
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
Common Options:
• -i, –ignore-case: Ignore case distinctions in both the PATTERN and the input files.
• -c, –count: Suppress normal output; instead print a count of matching lines for each input
file.
• -n, –line-number: Prefix each line of output with the 1-based line number within its input
file.
• -r, -R, –recursive: Read all files under each directory, recursively.
• -w, –word-regexp: Select only those lines containing matches that form whole words.
• -l, –files-with-matches: Suppress normal output; instead print the name of each input
file from which output would normally have been printed.
• -L, –files-without-match: Suppress normal output; instead print the name of each input
file from which no output would have been printed.
• -A <num>, –after-context=<num>: Print <num> lines of trailing context after matching lines.
• –include=<GLOB>: Search only files whose base name matches GLOB (e.g., –include="*.txt").
15
Comprehensive Linux Command Guide May 22, 2025
Common Options:
• -r, –reverse: Reverse the result of comparisons (sort in descending order).
• -n, –numeric-sort: Compare according to string numerical value.
• -f, –ignore-case: Fold lower case to upper case characters for comparisons (case-insensitive
sort).
• -u, –unique: With -c, check for strict ordering. Without -c, output only the first of an equal
run.
• -k POS1[,POS2], –key=POS1[,POS2]: Specify a sort key. Sort lines based on a specific field
(column). POS1 is the starting field, POS2 is the ending field (optional). Fields are 1-indexed.
• -t <char>, –field-separator=<char>: Use <char> as the field separator instead of whites-
pace. Example: -t’,’ for CSV files.
• -o <output_file>, –output=<output_file>: Write result to <output_file> instead of
standard output.
• -M, –month-sort: Compare as months (JAN < FEB < ... < DEC).
• -c, –check[=diagnose-first]: Check if the given file is already sorted. Do not sort; only
report if not sorted.
• -R, –random-sort: Shuffle input lines randomly. (Note: shuf command is also commonly
used for this).
Examples from Labs:
• sort filename > sorted_filename or sort -o sorted_filename filename
• Sorting numbers file: sort numbers (lexicographical), sort -n numbers (numerical).
• Sorting multiple files: sort numbers.txt words.txt
• Sorting CSV file data.csv by job column (e.g., 3rd column): sort -t’,’ -k3 data.csv
• Listing directory content and sorting by size (e.g., 5th field of ls -l): ls -l | sort -k5
-nr
16
Comprehensive Linux Command Guide May 22, 2025
Common Options:
• -b LIST, –bytes=LIST: Select only these bytes. LIST is a comma-separated list of byte
positions or ranges (e.g., 1-3, 5, 10-).
• -c LIST, –characters=LIST: Select only these characters. Similar to -b but for characters
(useful with multi-byte characters).
• -f LIST, –fields=LIST: Select only these fields. Also print any line that contains no delimiter
character, unless the -s option is specified.
• -d DELIM, –delimiter=DELIM: Use DELIM instead of TAB for field delimiter (for use with
-f). Example: -d’:’ or -d’,’.
• -s, –only-delimited: Do not print lines not containing delimiters (for use with -f).
• Extract first field (names) from "students" file (assuming space delimiter, may need -d’ ’):
cut -d’ ’ -f1 students
• Extract years of birth, sort, and print uniquely (e.g., if year is field 3, space delimited): cut
-d’ ’ -f3 students.txt | sort -u
Common Usage:
Common Options:
17
Comprehensive Linux Command Guide May 22, 2025
• -m, –chars: Print the character counts (can differ from bytes for multi-byte characters).
Example:
1 pwd ; ls -l ; date
2
• > (Overwrite): Redirects output to a file. If the file exists, it is overwritten. If it doesn’t exist,
it is created.
1 ls -l > file_listing . txt
2
• » (Append): Redirects output to a file. If the file exists, the new output is appended to the
end of the file. If it doesn’t exist, it is created.
1 date >> command_log . txt
2
18
Comprehensive Linux Command Guide May 22, 2025
6.4 Piping
Purpose: To send the standard output (stdout) of one command to become the standard input
(stdin) of another command. This allows for powerful chaining of commands. Operator:
• | (Pipe): Connects the output of command1 to the input of command2.
1 command1 | command2
2 ls -l | grep " . txt " # Lists files , then filters for
lines containing ". txt "
3 man -k " directory " | grep " create " # Finds man pages
related to " directory " , then filters for " create "
4 cat mydata . txt | sort | uniq > processed_data . txt # Sorts
data and removes duplicates
5
7 Package Management
Commands and tools for installing, upgrading, and removing software packages on Debian-based
systems like Linux Mint and Ubuntu.
Key Commands:
• sudo apt update: Resynchronizes the package index files from their sources. This updates
the local list of available packages and their versions. It should always be run before an
upgrade or install.
• sudo apt upgrade [package_name]: Upgrades all currently installed packages to their
newest versions. If a package_name is specified, only that package is upgraded. Does not
remove packages.
• sudo apt full-upgrade: Similar to upgrade, but may remove packages if required to
perform a complete upgrade of the system.
• sudo apt install <package_name>...: Installs one or more specified packages along
with their dependencies. Example: sudo apt install nano, sudo apt install gimp
inkscape
19
Comprehensive Linux Command Guide May 22, 2025
• sudo apt remove <package_name>...: Removes specified packages, but configuration files
may remain. Example: sudo apt remove gimp
• sudo apt purge <package_name>...: Removes packages AND their system-wide configu-
ration files. Example: sudo apt purge gimp
• sudo apt autoremove: Removes packages that were automatically installed to satisfy de-
pendencies for other packages and are now no longer needed.
• apt search <search_term>: Searches for packages matching the <search_term> in package
names and descriptions. (No sudo needed). Example: apt search "text editor"
• apt show <package_name>: Displays detailed information about a package, such as its
version, dependencies, and description. (No sudo needed). Example: apt show gimp
• apt list –upgradable: Lists all installed packages that have newer versions available for
upgrade.
• sudo apt install -f or sudo apt –fix-broken install: Attempts to correct broken
dependencies.
Note: Most apt commands that modify the system (install, remove, upgrade) require superuser
privileges, hence the use of sudo.
Key Actions/Options:
• dpkg -l [pattern], dpkg –list [pattern]: Lists installed packages matching pattern.
If no pattern, lists all.
20
Comprehensive Linux Command Guide May 22, 2025
The & runs the command in the background, freeing up your terminal. Key Features (within
the GUI):
Common Usage:
Description: Useful for verifying current user identity, especially when using sudo or su. The
user ID (UID) for the root user is always 0.
21
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
• sudo -i: Opens an interactive root login shell (full root environment).
• sudo -s: Opens an interactive root shell (retains more of the original user’s environment).
Important Note: Using sudo <command> is generally preferred over switching to a persistent
root shell (sudo su or sudo -i) for single commands, as it’s more secure (Principle of Least
Privilege) and better for auditing.
Common Usage:
• su (prompts for root password, switches to root user, keeps current environment largely
intact)
• su - or su -l or su –login (prompts for root password, switches to root user, and simulates
a full root login, including environment variables and home directory)
• su - <username> (switches to <username> with a login shell, prompts for their password)
• sudo su: Uses sudo to execute su. Switches to a root shell without needing the root password
(uses the current user’s password for sudo authentication). Similar to sudo -s.
Syntax (adduser):
22
Comprehensive Linux Command Guide May 22, 2025
• -m, –create-home: Create the user’s home directory if it does not exist.
• -d /path/to/home, –home-dir /path/to/home: Specify the path for the user’s home direc-
tory.
• -s /path/to/shell, –shell /path/to/shell: Specify the user’s login shell (e.g., -s /bin/bash).
• -g <group>, –gid <group>: Name or ID of the user’s initial primary group. The group must
exist.
• -c "Comment String", –comment "Comment String": GECOS field, typically used for the
user’s full name or description.
• -U, –user-group: Create a group with the same name as the user, and add the user to this
group (common default on some systems).
Example using useradd (for more manual control, often followed by passwd):
1 sudo useradd -m -s / bin / bash -g users -G sudo , dev -c " New
User " newusername
2
This will typically prompt for a password, full name, and other information.
Common Options:
Example:
1 sudo groupadd developers
2 sudo groupadd ali # Example for Lab 3 context
3
23
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
• passwd (by itself): Allows the current user to change their own password.
• sudo passwd <username>: Allows root (or sudoer) to set or change the password for
<username>. This is necessary after creating a user with useradd if a password wasn’t
set.
Common Options:
• -d, –delete: Delete a user’s password (make it empty). This allows login without a password
(not recommended for most accounts).
• -e, –expire: Expire a password, forcing the user to change it at their next login.
Common Usage:
Common Options:
• -R, –recursive: Operate on files and directories recursively. Essential for changing ownership
of an entire directory tree.
Example for Lab 3 (after creating user ’amine’ in group ’ali’ and home directory):
1 sudo chown -R amine : ali / home / amine
2
24
Comprehensive Linux Command Guide May 22, 2025
Common Options:
• -d /path/to/home, –home /path/to/home: Change the user’s home directory (use with -m
to move contents).
• -m, –move-home: Move content of the current home directory to the new home directory (used
with -d).
• -c "Comment", –comment "Comment": Change the GECOS field (user’s full name or descrip-
tion).
Common Usage:
• chfn (interactive mode for current user, prompts for each field).
• chfn -f "Full Name" <username> (changes only the full name for the specified user, or
current user if username omitted).
25
Comprehensive Linux Command Guide May 22, 2025
Common Usage:
• chsh (interactive mode for current user, prompts for the new shell).
• -l, –list-shells: Print the list of available shells from /etc/shells and exit.
Viewing available shells: The file /etc/shells lists valid login shells on the system.
1 cat / etc / shells
2
• /etc/shadow: Contains the encrypted passwords for user accounts and password aging
information. Readable only by root.
26
Comprehensive Linux Command Guide May 22, 2025
• /etc/group: Defines groups on the system. Each line includes: group name, group password
placeholder (x), group ID (GID), and a comma-separated list of member usernames.
• /etc/skel: A directory containing template files and directories that are copied to a new
user’s home directory when it’s created (e.g., by useradd -m or adduser). This provides
default configuration files (like .bashrc, .profile) for new users.
Note: There should be no spaces around the = sign. The command string should be enclosed
in single or double quotes.
• Getting help: For built-in shell commands like alias, use help.
1 help alias
2
Persistent Aliases: Aliases defined directly in the terminal are temporary and last only for
the current session. To make aliases permanent, add them to your shell’s configuration file. For
Bash, this is typically ~/.bashrc.
27
Comprehensive Linux Command Guide May 22, 2025
• ~/.bashrc: Read by Bash for interactive non-login shells. Common place for aliases, functions,
and PS1 customization.
• ~/.profile or ~/.bash_profile: Read by Bash for interactive login shells. Often sources ~/.bashrc
if it exists. Good for setting environment variables that should be available to all processes
started after login.
• /etc/profile: System-wide login shell configuration.
• /etc/bash.bashrc (or /etc/bashrc on some systems): System-wide non-login shell configuration.
The exact files and their interaction can vary slightly between distributions and shell configurations.
10 Wildcards (Globbing)
Purpose: Special characters used by the shell to match multiple file or directory names with a single
expression. This process is also known as "globbing". Common Wildcards:
28
Comprehensive Linux Command Guide May 22, 2025
Example for Backup (Lab 3): Backing up home directory and saving to an external device (conceptual
command, actual device path varies):
• gzip <filename>: Compresses <filename>, creating <filename>.gz and removing the original.
Usage with tar: Often, tar is used to bundle files, and then gzip is used to compress the resulting
.tar file, e.g., tar -cvf archive.tar files/ ; gzip archive.tar. However, modern tar usually includes
options (-z or -j) to do this in one step.
29
Comprehensive Linux Command Guide May 22, 2025
Note: Other tools like awk or combinations of head and tail can also achieve similar results for
printing specific lines. For example, to print line 38: head -n 38 filename.txt | tail -n 1. To
print lines 13-37: head -n 37 filename.txt | tail -n +13.
Conclusion
This guide has provided a comprehensive overview of essential Linux commands tailored to cover a
wide range of operations, from basic file navigation and management to text processing, package handling,
user administration, and shell customization. Mastering these commands forms a solid foundation
for effective work in a Linux environment. Remember that the man pages are an invaluable resource
for exploring the full capabilities and options of each command. Consistent practice is key to proficiency.
30