0% found this document useful (0 votes)
23 views30 pages

Lab 123

The Comprehensive Linux Command Guide provides essential commands for navigating the Linux file system, managing files and directories, and viewing file content. It covers commands such as pwd, cd, ls, man, mkdir, touch, rm, cp, mv, cat, head, tail, and less, detailing their purposes, syntax, common usage, and options. This guide serves as a valuable reference for users seeking to perform fundamental operations in a Linux environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views30 pages

Lab 123

The Comprehensive Linux Command Guide provides essential commands for navigating the Linux file system, managing files and directories, and viewing file content. It covers commands such as pwd, cd, ls, man, mkdir, touch, rm, cp, mv, cat, head, tail, and less, detailing their purposes, syntax, common usage, and options. This guide serves as a valuable reference for users seeking to perform fundamental operations in a Linux environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Comprehensive Linux Command

Guide
A Reference for Essential Operations

AI Generated Resource

May 22, 2025


Comprehensive Linux Command Guide May 22, 2025

Contents

2
Comprehensive Linux Command Guide May 22, 2025

1 File System Navigation and Information


This section covers commands essential for navigating the Linux file system and obtaining
information about its structure and your current location within it.

1.1 pwd - Print Working Directory


Purpose: Displays the full pathname of the current working directory. Syntax:
1 pwd [ OPTION ]...
2

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 (/).

1.2 cd - Change Directory


Purpose: Allows you to navigate between directories in the file system. Syntax:
1 cd [ OPTION ]... [ DIRECTORY ]
2

Common Usage and Special Arguments:


• cd <directory_name>: Moves to the specified directory (e.g., cd /home/user/documents).

• cd (no arguments): Changes to the current user’s home directory.

• cd ~: Explicitly changes to the home directory.

• cd ..: Moves to the parent directory (one level up).

• cd /: Moves to the root directory.

• cd -: Moves to the previously visited working directory.

1.3 ls - List Directory Contents


Purpose: Lists information about files and directories within the specified directory (or current
directory if none is specified). Syntax:
1 ls [ OPTION ]... [ FILE ]...
2

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

• -R, –recursive: Lists subdirectories recursively.

• -t: Sorts by modification time, newest first.

• -S: Sorts by file size, largest first.

• -r, –reverse: Reverses the current sort order.

• -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).

• -1 (The digit one): Lists one file per line.

Sorting and Order: By default, ls usually sorts entries alphabetically.

• To sort by modification time (newest first): ls -t

• To sort by modification time (oldest first): ls -ltr

• To sort by file size (largest first): ls -lS

• To display most recently modified files first: ls -lt

1.4 man - Manual Pages


Purpose: Displays the system’s online manual pages (man pages) for commands, system calls,
library functions, configuration files, etc. Syntax:
1 man [ OPTION ]... [ SECTION ] KEYWORD ...
2

Common Usage:

• man <command_name>: Example: man ls

• 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.

Navigating Man Pages:

• 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

1.5 clear - Clear Terminal Screen


Purpose: Clears the terminal screen of previous commands and output, providing a clean
workspace. Syntax:
1 clear [ OPTION ]...
2

Common Usage:
1 clear
2

Keyboard Shortcut: Often, Ctrl+L produces the same result.

2 File and Directory Management


Commands for creating, removing, copying, moving, and renaming files and directories.

2.1 mkdir - Make Directory


Purpose: Creates one or more new directories. Syntax:
1 mkdir [ OPTION ]... DIRECTORY ...
2

Common Usage:

• mkdir new_directory_name

• mkdir dir1 dir2 dir3 (to create multiple directories)

• mkdir -p path/to/my/deep/directory (to create parent directories as needed)

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.

• -v, –verbose: Print a message for each created directory.

• -m MODE, –mode=MODE: Set file mode (permissions) for the new directories, similar to chmod.

2.2 touch - Create or Update Files


Purpose: Creates an empty file if it does not exist. If the file already exists, it updates the
file’s access and modification timestamps to the current time. Syntax:
1 touch [ OPTION ]... FILE ...
2

Common Usage:

• touch filename.txt

• touch file1.txt file2.log file3.dat

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

2.3 rm - Remove Files or Directories


Purpose: Deletes files and directories. Use with extreme caution, especially with
options like -rf, as this command can permanently delete data without confirmation.
Syntax:
1 rm [ OPTION ]... FILE ...
2

Common Usage:

• rm filename.txt (removes a file)

• rm -r directory_name (removes a directory and its contents recursively)

• 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.

• -v, –verbose: Explain what is being done.

2.4 rmdir - Remove Empty Directories


Purpose: Removes (deletes) empty directories. It will not remove directories that contain any
files or other subdirectories. Syntax:
1 rmdir [ OPTION ]... DIRECTORY ...
2

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.

• –ignore-fail-on-non-empty: Do not report a failure if a directory to be removed is not


empty (by default, rmdir fails on non-empty directories).

2.5 cp - Copy Files and Directories


Purpose: Creates copies of files and directories. Syntax:
1 cp [ OPTION ]... SOURCE DEST
2 cp [ OPTION ]... SOURCE ... DIRECTORY
3

Common Usage:

6
Comprehensive Linux Command Guide May 22, 2025

• cp source_file destination_file

• cp source_file destination_directory/

• cp file1.txt file2.txt file3.txt target_directory/ (copies multiple files to a direc-


tory)

• cp -r source_directory/ destination_directory/ (copies a directory recursively)

• cp /etc/rsyslog.conf rsyslog.conf.bak (copies a system file to the current directory


with a new name)

Common Options:

• -r, -R, –recursive: Copy directories recursively. Essential for copying entire directory
structures.

• -i, –interactive: Prompt before overwriting an existing file at the destination.

• -p: Preserves file attributes such as mode (permissions), ownership, and timestamps.

• -v, –verbose: Explain what is being done.

• -a, –archive: Equivalent to -dR –preserve=all. Useful for making backups as it preserves
almost everything.

Behavior When Destination Exists:

• 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).

• If copying a directory (source_dir) to an existing directory (dest_dir) using cp -r source_dir


dest_dir, the source_dir itself (and its contents) will be copied inside dest_dir, resulting
in dest_dir/source_dir.

2.6 mv - Move or Rename Files and Directories


Purpose: Moves files or directories from one location to another, or renames them if the source
and destination are in the same location. Syntax:
1 mv [ OPTION ]... SOURCE DEST
2 mv [ OPTION ]... SOURCE ... DIRECTORY
3

Common Usage:

• mv old_filename.txt new_filename.txt (renames a file)

• mv old_dirname new_dirname (renames a directory)

• mv source_file.txt target_directory/ (moves a file into a directory)

• mv source_directory/ target_directory/ (moves a directory into another directory, if


target_directory exists)

• mv source_directory/ new_directory_name (renames source_directory to new_directory_name


if new_directory_name does not exist as a directory)

• mv dir1/file1.txt dir1/d1file1.txt (renames a file within its directory)

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.

• -f, –force: Do not prompt before overwriting. Use with caution.

• -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.

• -v, –verbose: Explain what is being done.


Behavior When Destination Exists:
• mv source_file existing_file: existing_file is typically overwritten by source_file
(unless -i or -n is used).

• mv source_directory existing_directory: If existing_directory exists, source_directory


is moved inside existing_directory, resulting in existing_directory/source_directory.

• mv source_directory non_existing_name: If non_existing_name does not exist as a


directory, source_directory is renamed to non_existing_name.
Moving and Renaming Simultaneously: To move a file and change its name, provide the
new path including the new file name as the destination. Example: mv /path/to/old_file.txt
/new/path/for/new_name.txt If a file with new_name.txt already exists in /new/path/for/,
it will be overwritten (subject to -i or -n).

3 Viewing File Content


Commands used to display the contents of text files in the terminal.

3.1 cat - Concatenate and Display Files


Purpose: Primarily used to display the entire content of one or more files. It can also be used
to concatenate (combine) files or create new files with redirected output. Syntax:
1 cat [ OPTION ]... [ FILE ]...
2

Common Usage:
• cat filename.txt (displays the content of filename.txt)

• cat file1.txt file2.txt (displays contents of file1.txt followed by file2.txt)

• cat file1.txt file2.txt > combined_file.txt (concatenates file1.txt and file2.txt,


and writes the result to combined_file.txt)

• cat > newfile.txt (allows typing text directly, which is then saved to newfile.txt upon
pressing Ctrl+D)

• cat » existing_file.txt (appends typed text to existing_file.txt)


Common Options:
• -n, –number: Number all output lines.

8
Comprehensive Linux Command Guide May 22, 2025

• -b, –number-nonblank: Number only non-empty output lines.

• -A, –show-all: Equivalent to -vET (shows non-printing characters, tabs as Î, and line endings
as $).

3.2 head - Display Start of Files


Purpose: Displays the first few lines (by default, 10 lines) of one or more files. Syntax:
1 head [ OPTION ]... [ FILE ]...
2

Common Usage:

• head filename.txt (displays the first 10 lines)

• head -n 20 filename.txt (displays the first 20 lines)

• head -c 100 filename.txt (displays the first 100 bytes)

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.

• -q, –quiet, –silent: Never print headers giving file names.

• -v, –verbose: Always print headers giving file names.

Example from Labs:

• Display the 10 first lines of a file: head -n 10 numtext.txt

• Save the 25 first lines to another file: head -n 25 numtext.txt > first25lines.txt

3.3 tail - Display End of Files


Purpose: Displays the last few lines (by default, 10 lines) of one or more files. Syntax:
1 tail [ OPTION ]... [ FILE ]...
2

Common Usage:

• tail filename.txt (displays the last 10 lines)

• tail -n 20 filename.txt (displays the last 20 lines)

• tail -c 100 filename.txt (displays the last 100 bytes)

• 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

• -c <bytes>, –bytes=<bytes>: Print the last <bytes> bytes.

• -f, –follow[={name|descriptor}]: Output appended data as the file grows. This is very
useful for monitoring log files.

• -q, –quiet, –silent: Never print headers giving file names.

• -v, –verbose: Always print headers giving file names.


Example from Labs:
• Display the 15 last lines of a file: tail -n 15 numtext.txt

3.4 less - Page Through File Content


Purpose: Displays file content one screenful at a time, allowing forward and backward navigation.
It is more advanced than more and does not need to read the entire file before starting. Syntax:
1 less [ OPTION ]... [ FILE ]...
2

Common Usage:
• less filename.txt
Interactive Commands (while less is running):
• Space bar or f or Ctrl+F: Scroll forward one screen.

• b or Ctrl+B: Scroll backward one screen.

• d or Ctrl+D: Scroll forward half a screen.

• u or Ctrl+U: Scroll backward half a screen.

• j or Down Arrow: Scroll forward one line.

• k or Up Arrow: Scroll backward one line.

• G: Go to the end of the file.

• g or 1G: Go to the beginning of the file.

• /<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.

• h: Display help screen with more commands.

• 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

4 Command-Line Text Editors


Text editors that run within the terminal, essential for editing configuration files, scripts, and
code directly on a server or in a terminal-based environment.

4.1 vi / vim - Visual Editor / Vi IMproved


Purpose: A powerful, modal text editor. vim is an enhanced version of vi with more features.
On most modern systems, typing vi often launches vim. Starting vi:
1 vi filename
2 vim filename
3 vi + filename # Opens file with cursor at the last line
4 vi + N filename # Opens file with cursor at line N
5

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:

• Switching to Insert Mode (from Command Mode):

– i: Insert text before the cursor.


– a: Append text after the cursor.
– I: Insert text at the beginning of the current line.
– A: Append text at the end of the current line.
– o: Open a new line below the current line and enter Insert Mode.
– O: Open a new line above the current line and enter Insert Mode.

• Returning to Command Mode: Press Esc.

• Saving and Quitting (Ex Mode commands, type : first from Command Mode):

– :w: Write (save) the file.


– :q: Quit (fails if there are unsaved changes).
– :wq or :x: Write (save) the file and quit.
– :q!: Quit without saving changes (force quit).
– ZZ (from Command Mode, no colon): Save and quit (if changes were made).
– ZQ (from Command Mode, no colon): Quit without saving (similar to :q!).

Navigation (in Command Mode):

• Arrow Keys: Usually work for basic navigation.

• h: Move cursor left.

11
Comprehensive Linux Command Guide May 22, 2025

• j: Move cursor down.

• k: Move cursor up.

• l: Move cursor right.

• w: Move to the start of the next word.

• b: Move to the start of the previous word.

• e: Move to the end of the current word.

• 0 (zero): Move to the beginning of the current line.

• ˆ: Move to the first non-blank character of the current line.

• $: Move to the end of the current line.

• G: Go to the last line of the file.

• gg or 1G: Go to the first line of the file.

• <N>G or :<N>: Go to line number <N> (e.g., 10G or :10).

• Ctrl+F: Page down.

• Ctrl+B: Page up.

• Ctrl+D: Scroll down half a screen.

• Ctrl+U: Scroll up half a screen.

Editing Text (in Command Mode):

• Deleting:

– x: Delete character under the cursor.


– X: Delete character before the cursor.
– dw: Delete word (from cursor to the end of the word).
– db: Delete word backward.
– dd: Delete the current line. (Prefix with a number to delete multiple lines, e.g., 8dd deletes
8 lines).
– D or d$: Delete from the cursor to the end of the line.

• Changing (deletes text and enters Insert Mode):

– cw: Change word.


– cc or S: Change entire line.
– C or c$: Change from cursor to end of line.
– s: Substitute character under cursor and enter Insert Mode.
– r<char>: Replace single character under cursor with <char> (stays in Command Mode).
– R: Enter Replace Mode (overwrite characters as you type, press Esc to exit).

• Copying (Yanking) and Pasting (Putting):

– 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

– yw: Yank word.


– p: Put (paste) the yanked/deleted text after the cursor/line.
– P: Put (paste) the yanked/deleted text before the cursor/line.

• Undo/Redo:

– u: Undo the last change.


– U: Undo all changes on the current line (revert line to original state).
– Ctrl+R: Redo the last undone change.

• Change Case:

– ~: Toggle case of the character under the cursor and move to the next character.

Searching and Replacing (Searching in Command Mode, Replacing in Ex Mode):

• Searching:

– /<pattern>: Search forward for pattern.


– ?<pattern>: Search backward for pattern.
– n: Repeat the last search in the same direction.
– N: Repeat the last search in the opposite direction.
– To ignore case: /pattern\c or set :set ic (ignorecase). To turn off: :set noic.

• Replacing (Substitution - Ex Mode command, type : first): Format: :[range]s/old_pattern/new_s

• 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.

4.2 nano - User-Friendly Text Editor


Purpose: A simple, modeless, and user-friendly command-line text editor, often recommended
for beginners or for quick edits. Starting nano:
1 nano [ OPTIONS ] [[+ LINE [ , COLUMN ]] FILE ]...
2 nano filename . txt
3 nano + LINE_NUMBER filename . txt # Opens file and places
cursor on LINE_NUMBER
4

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

5 Text Processing and Analysis


Commands for searching, filtering, sorting, and transforming text data within files or from
command output.

5.1 grep - Global Regular Expression Print


Purpose: Searches for lines containing a match to a specified pattern (often a regular expression)
in files or standard input. Syntax:
1 grep [ OPTIONS ] PATTERN [ FILE ...]
2

Common Usage:

• grep "search_string" filename.txt

• grep "pattern" file1.txt file2.txt

• ls -l | grep "keyword" (searches for "keyword" in the output of ls -l)

Common Options:

• -i, –ignore-case: Ignore case distinctions in both the PATTERN and the input files.

• -v, –invert-match: Select non-matching lines.

• -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.

• -E, –extended-regexp: Interpret PATTERN as an extended regular expression (ERE). Useful


for more complex patterns like ‘|‘ (OR).

• -A <num>, –after-context=<num>: Print <num> lines of trailing context after matching lines.

• -B <num>, –before-context=<num>: Print <num> lines of leading context before matching


lines.

• -C <num>, –context=<num>: Print <num> lines of output context (equivalent to -A <num> -B


<num>).

• –include=<GLOB>: Search only files whose base name matches GLOB (e.g., –include="*.txt").

• –exclude=<GLOB>: Skip files whose base name matches GLOB.

Regular Expressions (Basic Examples for Lab Context):

15
Comprehensive Linux Command Guide May 22, 2025

• p̂attern: Lines starting with "pattern". Example: grep ’ˆ


[aA]’ filename
• pattern$: Lines ending with "pattern". Example: grep ’rs$’ filename
• [abc]: Any one character from the set a, b, c. Example: grep ’[ BEQ]′ f ilename
• [0-9]: Any digit. Example: grep ’[0-9]’ filename
• .: Matches any single character (except newline). Example: grep ’. r′ f ilename

• *: Matches the preceding item zero or more times.


• To search for multiple words (OR condition): grep -E ’word1|word2’ filename or
grep -e word1 -e word2 filename

5.2 sort - Sort Lines of Text Files


Purpose: Sorts lines of text files alphabetically, numerically, or by other criteria. Syntax:
1 sort [ OPTION ]... [ FILE ]...
2

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

5.3 cut - Remove Sections from Each Line of Files


Purpose: Extracts specific sections (columns, fields, or characters/bytes) from each line of a
file or standard input. Syntax:
1 cut OPTION ... [ FILE ]...
2

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).

Examples from Labs:

• Extract first field (names) from "students" file (assuming space delimiter, may need -d’ ’):
cut -d’ ’ -f1 students

• Extract fields 2, 3, and 4: cut -d’ ’ -f2,3,4 students

• Extract first 3 bytes: cut -b 1-3 students.txt

• Extract bytes from 13 to 20: cut -b 13-20 students.txt

• Extract bytes from 20 to end of line: cut -b 20- students.txt

• Extract years of birth, sort, and print uniquely (e.g., if year is field 3, space delimited): cut
-d’ ’ -f3 students.txt | sort -u

5.4 wc - Word, Line, and Character Count


Purpose: Counts lines, words, and bytes/characters in specified files or from standard input.
Syntax:
1 wc [ OPTION ]... [ FILE ]...
2

Common Usage:

• wc filename.txt (displays lines, words, and byte count)

Common Options:

• -l, –lines: Print the newline counts.

• -w, –words: Print the word counts.

• -c, –bytes: Print the byte counts.

17
Comprehensive Linux Command Guide May 22, 2025

• -m, –chars: Print the character counts (can differ from bytes for multi-byte characters).

Examples from Labs:

• Count characters in "lines13-37.txt": wc -m lines13-37.txt (or wc -c for bytes)

• Count words in "lines13-37.txt": wc -w lines13-37.txt

• Count lines in "lines13-37.txt": wc -l lines13-37.txt

• Count characters from input redirection: wc -c < test2.txt

• Count lines from pipe: grep "string" numtext.txt | wc -l

6 Shell Operations and Scripting Primitives


Features of the shell that allow for more complex command interactions, including redirection of
input/output and chaining commands.

6.1 Sequential Command Execution


Purpose: To execute multiple commands one after another in a single command line. Method:
Use a semicolon (;) to separate commands. Each command runs to completion before the next
one starts, regardless of the success or failure of the previous command. Syntax:
1 command1 ; command2 ; command3
2

Example:
1 pwd ; ls -l ; date
2

6.2 Output Redirection


Purpose: To redirect the standard output (stdout) of a command to a file instead of the
terminal screen. Operators:

• > (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.3 Input Redirection


Purpose: To redirect the standard input (stdin) of a command to come from a file instead of
the keyboard. Operator:
• < (Input from file): Takes input from the specified file.
1 wc -l < mydocument . txt # Counts lines in mydocument . txt
2 sort < unsorted_data . txt > sorted_data . txt
3

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.

7.1 apt - Advanced Package Tool


Purpose: A powerful command-line tool for managing software packages. It handles dependen-
cies automatically and interacts with software repositories. Syntax (Common Commands):
1 sudo apt [ OPTION ] COMMAND [ PACKAGE_NAME ...]
2

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 –installed: Lists all packages installed on the system.

• 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.

7.2 dpkg - Debian Package Manager


Purpose: A lower-level tool that handles individual Debian package files (.deb files). apt is
generally preferred for installations from repositories as it handles dependencies better. dpkg is
often used for installing .deb files downloaded manually. Syntax (Common Commands):
1 sudo dpkg [ OPTION ]... ACTION [ PACKAGE_FILE . deb | PACKAGE_NAME
]
2

Key Actions/Options:

• sudo dpkg -i <package_file.deb>, sudo dpkg –install <package_file.deb>: Installs


a downloaded .deb package file. If there are missing dependencies, dpkg will error, and you
might need to run sudo apt install -f to fix them. Example for installing Google Chrome:
sudo dpkg -i google-chrome-stable_current_amd64.deb

• sudo dpkg -r <package_name>, sudo dpkg –remove <package_name>: Removes an in-


stalled package (leaves configuration files).

• sudo dpkg -P <package_name>, sudo dpkg –purge <package_name>: Purges an installed


package (removes package and its configuration files).

• dpkg -l [pattern], dpkg –list [pattern]: Lists installed packages matching pattern.
If no pattern, lists all.

• dpkg -s <package_name>, dpkg –status <package_name>: Shows the status of a specified


package.

• dpkg -L <package_name>: Lists files installed by the specified package.

20
Comprehensive Linux Command Guide May 22, 2025

7.3 Synaptic Package Manager


Purpose: A graphical user interface (GUI) for apt, providing a more visual way to manage
software packages. Launching Synaptic: From the command line, Synaptic can typically be
launched using:
1 synaptic &
2 sudo synaptic & # Or often just ’ synaptic & ’ and it will
prompt for password
3

The & runs the command in the background, freeing up your terminal. Key Features (within
the GUI):

• Searching for packages by name, description, or category.

• Browse available packages.

• Marking packages for installation, reinstallation, upgrade, or removal.

• Applying changes to install/remove marked packages and their dependencies.

• Reloading package information (similar to apt update).

8 User and Group Management


Commands for managing user accounts, groups, and permissions. Many of these commands
require superuser privileges (sudo).

8.1 id - Print User and Group IDs


Purpose: Displays real and effective user and group IDs, and supplementary group memberships.
Syntax:
1 id [ OPTION ]... [ USER ]
2

Common Usage:

• id (displays information for the current user)

• id <username> (displays information for the specified user)

• id -u (prints only the effective user ID number)

• id -un (prints only the effective user name)

• id -g (prints only the effective group ID number)

• id -gn (prints only the effective group name)

• id -G (prints all group ID numbers)

• id -Gn (prints all group names)

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

8.2 sudo - Execute a Command as Another User


Purpose: Allows a permitted user to execute a command as the superuser (root) or as another
specified user, as defined by the /etc/sudoers file. Syntax:
1 sudo [ OPTIONS ] COMMAND [ ARGUMENTS ...]
2 sudo -s [ COMMAND ]
3 sudo -i [ COMMAND ]
4

Common Usage:

• sudo <command_to_run_as_root>: Example: sudo apt update

• sudo -u <other_username> <command>: Run command as <other_username>.

• 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.

8.3 su - Substitute User


Purpose: Changes the current user ID to that of another user. If no username is specified, it
defaults to switching to the superuser (root). Syntax:
1 su [ OPTIONS ...] [ -] [ USER [ ARG ...]]
2

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>, prompts for their password, keeps environment)

• 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.

• sudo su -: Similar to sudo -i. Switches to a root login shell.

8.4 useradd / adduser - Create New User


Purpose: Creates a new user account. adduser is often a more user-friendly frontend to the
lower-level useradd utility, especially on Debian-based systems. adduser may interactively
prompt for information and create a home directory by default. Syntax (useradd):
1 sudo useradd [ OPTIONS ] LOGIN
2

Syntax (adduser):

22
Comprehensive Linux Command Guide May 22, 2025

1 sudo adduser [ OPTIONS ] LOGIN


2

Common useradd Options (often used in scripts or for precise control):

• -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.

• -G <group1,group2...>, –groups <group1,group2...>: A list of supplementary groups


the user will also be a member of. Groups 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

Example using adduser (more interactive, common for manual creation):


1 sudo adduser newusername
2

This will typically prompt for a password, full name, and other information.

8.5 groupadd - Create New Group


Purpose: Creates a new user group. Syntax:
1 sudo groupadd [ OPTIONS ] GROUP
2

Common Options:

• -g GID, –gid GID: Use GID for the new group.

Example:
1 sudo groupadd developers
2 sudo groupadd ali # Example for Lab 3 context
3

23
Comprehensive Linux Command Guide May 22, 2025

8.6 passwd - Manage User Passwords


Purpose: Sets or changes passwords for user accounts. Syntax:
1 passwd [ OPTIONS ] [ LOGIN ]
2 sudo passwd [ OPTIONS ] LOGIN # To change another user ’ s
password
3

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:

• -l, –lock: Lock the named account (password locking).

• -u, –unlock: Unlock the named account.

• -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.

• -S, –status: Report password status on the named account.

8.7 chown - Change File Owner and Group


Purpose: Changes the user and/or group ownership of files and directories. Syntax:
1 sudo chown [ OPTIONS ] NEW_OWNER [: NEW_GROUP ] FILE ...
2

Common Usage:

• sudo chown <new_user> <file_or_directory>: Changes only the user owner.

• sudo chown <new_user>:<new_group> <file_or_directory>: Changes both user and group


owner.

• sudo chown :<new_group> <file_or_directory>: Changes only the group owner.

Common Options:

• -R, –recursive: Operate on files and directories recursively. Essential for changing ownership
of an entire directory tree.

• -v, –verbose: Output a diagnostic for every file processed.

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

8.8 usermod - Modify User Account


Purpose: Modifies an existing user account’s attributes. Syntax:
1 sudo usermod [ OPTIONS ] LOGIN
2

Common Options:

• -l <new_login>, –login <new_login>: Change the user’s login name.

• -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).

• -s /path/to/shell, –shell /path/to/shell: Change the user’s login shell.

• -g <group>, –gid <group>: Change the user’s primary group.

• -G <group1,group2...>, –groups <group1,group2...>: Set the user’s list of supplemen-


tary groups. This overwrites existing supplementary groups.

• -aG <group1,group2...>, –append –groups <group1,group2...>: Add the user to sup-


plementary groups specified, without removing them from existing ones. The -a (append)
option must be used with -G.

• -c "Comment", –comment "Comment": Change the GECOS field (user’s full name or descrip-
tion).

• -L, –lock: Lock a user’s password.

• -U, –unlock: Unlock a user’s password.

Example (adding user to a supplementary group):


1 sudo usermod - aG sudo someuser # Adds ’ someuser ’ to the ’
sudo ’ group
2

8.9 chfn - Change User Information (GECOS)


Purpose: Changes a user’s "GECOS" information, which typically includes their full name,
room number, work phone, and home phone. This information is stored in the /etc/passwd file.
Syntax:
1 chfn [ OPTIONS ] [ USERNAME ]
2

Common Usage:

• chfn (interactive mode for current user, prompts for each field).

• sudo chfn <username> (interactive mode for specified user).

• 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

• chfn -r "Room Number" <username>

• chfn -w "Work Phone" <username>

• chfn -h "Home Phone" <username>


Common Options:
• -f, –full-name <FULL_NAME>

• -r, –room <ROOM_NUMBER>

• -w, –work-phone <WORK_PHONE>

• -h, –home-phone <HOME_PHONE>

• -o, –other <OTHER>

8.10 chsh - Change Login Shell


Purpose: Changes a user’s login shell (the default command interpreter started after login).
Syntax:
1 chsh [ OPTIONS ] [ LOGIN ]
2

Common Usage:
• chsh (interactive mode for current user, prompts for the new shell).

• sudo chsh <username> (interactive mode for specified user).

• chsh -s /path/to/new/shell (changes current user’s shell non-interactively).

• sudo chsh -s /path/to/new/shell <username> (changes specified user’s shell).


Common Options:
• -s SHELL, –shell SHELL: Specify the new login shell. The shell must typically be listed in
/etc/shells.

• -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

8.11 User and Group Configuration Files (Conceptual)


Understanding these files is crucial for manual user management and troubleshooting. Direct
editing requires extreme care; using utilities like vipw or vigr is safer if direct editing is
unavoidable.
• /etc/passwd: Contains user account information. Each line represents a user and typically
includes: username, encrypted password placeholder (x), user ID (UID), group ID (GID),
GECOS (user’s full name, etc.), home directory, and login shell.

• /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.

9 Shell Customization and Features


Enhancing productivity and customizing the command-line environment using shell features.

9.1 Command Aliases


Purpose: Create shortcuts or alternative names for commands or sequences of commands. This
is useful for frequently used commands or complex commands with many options. Commands:

• alias: Displays a list of all currently defined aliases.


1 alias
2

• Defining an alias: alias <name>=’<command_string>’


1 alias ll = ’ ls - alhF ’
2 alias lsu = ’ ls / usr ’
3 alias print_time = ’ date +"% T " ’ # % T is hh : mm : ss
4

Note: There should be no spaces around the = sign. The command string should be enclosed
in single or double quotes.

• unalias <name>: Removes the alias specified by <name>.


1 unalias ll
2

• 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.

1. Open ~/.bashrc in a text editor (e.g., nano ~/.bashrc).


2. Add your alias definitions (e.g., alias lsu=’ls /usr’) to the file, often in a dedicated
section for aliases.
3. Save the file and exit the editor.
4. To apply the changes to the current terminal session, source the file: source ~/.bashrc or .
~/.bashrc. New terminal sessions will automatically load these aliases.

27
Comprehensive Linux Command Guide May 22, 2025

9.2 Environment Variables


Purpose: Dynamic-named values that can affect the way running processes will behave on a
computer. Defining and Accessing Variables:
• Setting a variable (for current session): VARIABLEN AM E = ”value”

9.3 Shell Configuration Files (Brief Overview)


These files are sourced by the shell at different times and control its behavior and environment.

• ~/.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.

9.4 Useful Keyboard Shortcuts (Bash)


These shortcuts enhance command-line editing efficiency.

• Ctrl+A: Move cursor to the beginning of the line.


• Ctrl+E: Move cursor to the end of the line.
• Ctrl+P or Up Arrow: Show previous command from history.
• Ctrl+N or Down Arrow: Show next command from history.
• Ctrl+U: Erase from the cursor to the beginning of the line.
• Ctrl+K: Erase from the cursor to the end of the line.
• Ctrl+W: Erase the word before the cursor.
• Ctrl+L: Clear the terminal screen (similar to the clear command).
• Ctrl+R: Reverse search through command history. Start typing part of a command, and matches
will appear.
• Tab: Autocomplete command names, file paths, or variable names. Pressing twice may show possible
completions.
• Alt+. (or Esc .): Insert the last argument of the previous command.

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:

• * (Asterisk): Matches any sequence of characters, including an empty sequence.


– ls *.txt: Lists all files ending with .txt.
– ls /etc/rc* : Lists all files in /etc starting with rc.
– rm data*: Removes all files starting with "data".
• ? (Question Mark): Matches any single character.
– ls file?.dat: Matches file1.dat, fileA.dat, etc., but not file10.dat.
– ls ???.txt: Lists all files with exactly three characters before the .txt extension.
• [...] (Square Brackets): Matches any one of the characters enclosed in the brackets. A range
can be specified with a hyphen (e.g., [a-z], [0-9]).
– ls file[123].txt: Matches file1.txt, file2.txt, or file3.txt.
– ls [abc]*.doc: Matches files starting with ’a’, ’b’, or ’c’ and ending with .doc.
– ls *.[c h] : M atchesf ilesnotendingwith′ .c′ or′ .h′ (if extglobisnotset, !canbeusedinsidef ornegationwithsomeshells/settin

28
Comprehensive Linux Command Guide May 22, 2025

11 File Compression and Archiving


Tools for bundling multiple files into a single archive file and for compressing files to save disk
space.

11.1 tar - Tape Archive


Purpose: Creates, lists, and extracts archive files (tarballs). It bundles multiple files and directories
into a single file but does not compress by default. Compression is usually handled by options or
by piping to a compression utility. Common Operations:

• Create an archive: tar -cvf <archive_name.tar> <file1> <file2> <directory1> ...


– c: Create a new archive.
– v: Verbose mode (show files being processed).
– f <filename>: Specify the archive filename.
• Create a compressed archive (gzipped - .tar.gz or .tgz): tar -cvzf <archive_name.tar.gz> ...
– z: Filter the archive through gzip (compress/decompress).
• Create a compressed archive (bzipped2 - .tar.bz2 or .tbz2): tar -cvjf <archive_name.tar.bz2>
...
– j: Filter the archive through bzip2.
• Extract an archive: tar -xvf <archive_name.tar>
– x: Extract files from an archive.
• Extract a compressed archive (gzipped): tar -xvzf <archive_name.tar.gz>
• Extract a compressed archive (bzipped2): tar -xvjf <archive_name.tar.bz2>
• List archive contents: tar -tvf <archive_name.tar> (or -tzvf, -tjvf for compressed)
– t: List the contents of an archive.
• Extract to a specific directory: tar -xvf <archive.tar> -C /path/to/destination
– -C <directory>: Change to <directory> before performing any operations.

Example for Backup (Lab 3): Backing up home directory and saving to an external device (conceptual
command, actual device path varies):

1 sudo tar - cvzpf / mnt / external_drive / home_backup_$ ( date +% Y %


m % d ) . tar . gz / home / your_username
2 # -p preserves permissions
3 # $ ( date +% Y % m % d ) adds current date to filename
4

11.2 gzip / gunzip - GNU Zip


Purpose: Compresses or decompresses files (typically single files). gzip replaces the original
file with a compressed version having a .gz extension. Commands:

• gzip <filename>: Compresses <filename>, creating <filename>.gz and removing the original.

1 gzip myfile . txt # Results in myfile . txt . gz


2

• gzip -k <filename>: Compresses <filename>, but keeps the original file.


• gunzip <filename.gz> or gzip -d <filename.gz>: Decompresses <filename.gz>, creating <filename>
and removing the .gz file.

1 gunzip myfile . txt . gz # Results in myfile . txt


2

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

12 Advanced Text Manipulation with sed


The sed (Stream EDitor) command is powerful for performing basic text transformations on an input
stream (a file or input from a pipeline). While basic substitution was covered earlier, sed is also
useful for printing specific lines.

12.1 sed - Printing Specific Lines


Purpose: To select and print only specific lines or ranges of lines from a file. Common Usage for
Printing:

• Print a specific line number (e.g., line 38):

1 sed -n ’ 38 p ’ filename . txt


2 # -n : Suppress automatic printing of pattern space
3 # p : Print the current pattern space
4

• Print a range of lines (e.g., lines 13 to 37):

1 sed -n ’ 13 ,37 p ’ filename . txt


2

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

You might also like