unit 2 linux
unit 2 linux
Linux sessions:-
In Linux, a session refers to a period of interaction between a user and the system,
encompassing activities like logging in, executing commands, and using system resources.
Sessions can be local, graphical, or remote, and they help manage user environments and
processes.
In summary, Linux sessions enable user interaction with the system, whether locally or
remotely, and manage processes, configurations, and user environments. Tools like tmux,
screen, and nohup help manage and persist sessions, while systemd handles modern
session management.
Standard streams ;-
In Linux (and Unix-like systems), standard streams refer to three predefined channels that
allow communication between processes and the operating system. These streams are
commonly used for input, output, and error reporting. The three standard streams are:
• File Descriptor: 0
• Description: Standard input is the stream from which a process reads data. By
default, this is usually the keyboard, but it can also be redirected from files or other
processes.
• Usage Example: When you run a command and it asks for input, it reads from the
standard input (e.g., typing text in a terminal).
• Redirection: You can redirect input from a file using the < operator:
• File Descriptor: 1
• Description: Standard output is the stream to which a process writes its output. By
default, this is the terminal or console screen.
• Usage Example: When you run a command like echo "Hello, World!", it
outputs the result to the standard output (i.e., your terminal).
• Redirection: You can redirect output to a file using the > operator:
echo "Hello, World!" > output.txt
• File Descriptor: 2
• Description: Standard error is the stream used for error messages and diagnostics.
It's separate from standard output, allowing errors to be directed to a different
location than regular output.
• Usage Example: Errors from commands, like file not found or permission denied,
are written to standard error.
• Redirection: You can redirect errors to a file using the 2> operator:
command_that_fails 2> error.log
• Redirecting both stdout and stderr: To redirect both standard output and standard
error to the same file, you can use:
• Pipes (|): You can use pipes to connect the output of one command to the input of
another:
command1 | command2
In this case, the output of command1 (stdout) becomes the input (stdin) of command2.
Summary:
These standard streams are fundamental for shell scripting, command execution, and
process management, providing flexibility for data manipulation and error handling.
Redirection
Redirection in Linux is the process of controlling where the output of a command goes
(standard output) or where input comes from (standard input). It allows you to change the
default behavior of where data is read from or written to, enabling more complex
operations in shell scripting and command-line tasks.
Redirection helps manage command input/output, allowing efficient data handling, error
capture, and automation in scripts.
Pipes
Pipes in Linux (|) are used to pass the output of one command as input to another,
enabling you to chain commands together for more complex tasks.
Key Points:
• Basic Pipe (|): Passes standard output from one command to standard input of
another. Example: ls | grep "file" filters the list of files containing "file".
• Chaining Commands: Multiple commands can be linked with pipes. Example: ps
aux | grep "bash" | wc -l lists processes, filters by "bash", and counts
results.
• Redirection with Pipes: Use tee to send output to both the terminal and a file.
Example: ls | tee output.txt.
• Pipes with Standard Error: 2>&1 can be used to pipe both output and error
streams.
Benefits:
Pipes are essential for creating efficient and flexible workflows in the command line.
Tee command:-
The tee command in Linux is used to read from standard input and write to both
standard output (stdout) and one or more files simultaneously. It allows you to capture
the output of a command and save it to a file while still displaying it in the terminal.
Syntax:
bash
Copy code
command | tee [options] file
Key Options:
bash
Copy code
echo "Hello" | tee -a output.txt
bash
Copy code
some_command | tee -i output.txt
Examples:
1. Basic Usage:
bash
Copy code
ls | tee output.txt
This will list the files in the current directory (ls), display the output in the terminal, and
save it to output.txt.
2. Appending to a File:
bash
Copy code
echo "New line" | tee -a output.txt
This appends "New line" to the output.txt file, while still displaying it on the terminal.
3. Multiple Files:
bash
Copy code
ls | tee file1.txt file2.txt
This writes the output of ls to both file1.txt and file2.txt, as well as displaying it on
the terminal.
bash
Copy code
ps aux | tee process_log.txt | grep "bash"
This shows all running processes (ps aux), saves them to process_log.txt, and pipes
the output to grep to filter processes related to "bash".
Summary:
• tee allows you to capture output and save it to a file while still displaying it in the
terminal.
• It is useful for logging command outputs or debugging without losing visibility in the
terminal.
• Options like -a (append) and -i (ignore interrupts) provide additional flexibility.
Command execution :-
Command execution in Linux involves running a command in the shell, where the shell
interprets, looks up, and executes it. Here's a summary:
1. Command Types:
a. Built-in: Commands like cd or echo, executed directly by the shell.
b. External: Programs found in directories listed in the $PATH variable (e.g., ls,
grep).
2. Process:
a. The shell parses the command, checks if it's built-in or external, and then
executes it.
3. Exit Status:
a. A return code is provided after execution (0 for success, non-zero for failure).
Check with $?.
4. Background Execution (&):
a. Run commands in the background by appending &.
5. Job Control:
a. Use fg, bg, and jobs for managing background jobs.
6. Redirection and Piping:
a. Redirection changes input/output locations (e.g., > for output redirection).
b. Piping (|) passes output from one command to another.
7. Sudo:
a. Run commands with elevated privileges using sudo.
Command execution in Linux is fundamental for interacting with the system, allowing for
efficient task management and automation.
1. Text Navigation:
a. Arrow keys:
i. Up/Down: Cycle through the command history.
ii. Left/Right: Move the cursor left or right within the command.
b. Ctrl + A: Move the cursor to the beginning of the line.
c. Ctrl + E: Move the cursor to the end of the line.
d. Ctrl + U: Delete from the cursor to the beginning of the line.
e. Ctrl + K: Delete from the cursor to the end of the line.
f. Ctrl + W: Delete the word before the cursor.
g. Ctrl + L: Clear the terminal screen (like typing clear).
2. Editing Commands:
a. Backspace: Delete the character to the left of the cursor.
b. Delete: Remove the character under the cursor.
c. Ctrl + D: Delete the character under the cursor or exit the shell if the line is
empty.
d. Ctrl + H: Acts like backspace.
e. Ctrl + T: Swap the character before the cursor with the character under the
cursor.
3. History Navigation:
a. Ctrl + R: Reverse search through the command history. Pressing it multiple
times cycles through previous commands matching the search.
b. Ctrl + P: Previous command (same as the up arrow).
c. Ctrl + N: Next command (same as the down arrow).
d. !!: Repeat the last command.
e. !n: Execute the nth command from history (e.g., !3 for the third command).
4. Autocomplete:
a. Tab: Press once to autocomplete file or command names. Press twice for
suggestions.
b. Ctrl + I: Another shortcut for autocomplete (works similarly to Tab).
5. Cut, Paste, and Copy:
a. Ctrl + Y: Paste the most recently cut text (e.g., from Ctrl + W or Ctrl + U).
b. Ctrl + X followed by Ctrl + C: Cuts the selected text.
6. Search and Replace:
a. Ctrl + W: Search for a word in the command line from the cursor position
backward.
b. Ctrl + S: Search forward in the command line.
7. Canceling Commands:
a. Ctrl + C: Cancel the current command or process.
b. Ctrl + Z: Suspend the current process (can be resumed with fg).
8. Line Editing Mode (Emacs vs. Vi):
a. Emacs Mode: By default, most Linux shells (like Bash) use Emacs-style key
bindings for command line editing.
b. Vi Mode: You can switch to Vi-style editing by typing set -o vi in the
terminal. In Vi mode, the command line behaves like the Vi editor with
different keystrokes for navigation and editing.
Quotes:-
In Linux, quotes are used to control how the shell interprets text, particularly special
characters and variables.
Types of Quotes:
1. Single Quotes ('): Preserve everything literally inside, including spaces and special
characters.
a. Example: echo 'Hello $USER' → Hello $USER
2. Double Quotes ("): Allow variable and command substitution, but preserve most
other characters.
a. Example: echo "Hello $USER" → Hello username (where $USER is
expanded)
3. Backticks (`): Used for command substitution; executes the command inside and
replaces the backticks with the output.
a. Example: echo "Current directory: pwd" → Current directory:
/home/user
4. Escape (\): Escapes special characters to treat them literally.
a. Example: echo "This is a quote: \"Hello\"" → This is a quote:
"Hello"
Summary:
These quoting mechanisms help manage how input is parsed and executed in the shell.
Command subsitution:-
Command substitution in Linux allows you to execute a command and substitute its
output directly into another command. This is useful for incorporating the results of one
command into another without needing to store the output in a file or variable manually.
Syntax:
1. Backticks (`):
bash
Copy code
command1 `command2`
bash
Copy code
command1 $(command2)
a. This is the preferred syntax because it is more readable and allows nesting
commands.
Example with Backticks:
bash
Copy code
echo "Today is `date`"
Output:
csharp
Copy code
Today is Thu Nov 28 12:34:56 UTC 2024
• The date command is executed and its output is substituted into the echo
command.
bash
Copy code
echo "Today is $(date)"
Output:
csharp
Copy code
Today is Thu Nov 28 12:34:56 UTC 2024
• This command first executes pwd to get the current directory, then executes ls on
that directory and substitutes the result.
Advantages of $() over Backticks:
Summary:
• Command substitution allows you to use the output of one command inside
another.
• The syntax can be either backticks (`) or $(...), with the latter being preferred for
better readability and ease of nesting.
• It's a powerful tool for automating tasks and combining commands.
Job control:-
Job control in Linux allows you to manage processes running in the background or
foreground. Key commands include:
Job control enables multitasking, letting you run, suspend, resume, and terminate
processes from the shell.
Aliases:-
Aliases in Linux are shortcuts for longer commands or frequently used command
sequences, making it easier and faster to execute common tasks.
Key Points:
1. Creating an Alias:
a. Use the alias command to create a shortcut.
b. Example:
bash
Copy code
alias ll='ls -l'
3. Removing an Alias:
a. Use unalias to remove an alias.
b. Example:
bash
Copy code
unalias ll
4. Persistent Aliases:
a. To make aliases permanent, add them to your shell's configuration file
(e.g., .bashrc for Bash).
b. Example:
bash
Copy code
echo "alias ll='ls -l'" >> ~/.bashrc
Variables:-
Variables in Linux are used to store and manage data, such as system information, user
input, or environment settings, which can then be used by commands, scripts, and
applications.
1. Environment Variables:
a. These variables store information about the system environment and affect
the behavior of processes.
b. Examples include:
i. $HOME: The current user's home directory.
ii. $PATH: A list of directories the shell searches for executable files.
iii. $USER: The name of the current user.
c. You can view environment variables using the printenv or echo command.
bash
Copy code
echo $HOME
2. Shell Variables:
a. Shell variables are temporary and are typically used within a shell session or
script.
b. You can create a shell variable like this:
bash
Copy code
my_var="Hello"
echo $my_var
6. Variable Expansion:
a. $variable_name: Expands the value of a variable.
b. ${variable_name}: Used when the variable is followed by other characters
that could be interpreted as part of the variable name.
i. Example:
bash
Copy code
path="/usr/local/bin"
echo ${path}/program
Predefined variables:-
redefined variables in Linux are system-set variables that provide important information
about the environment, shell, or script execution. Key examples include:
These variables are automatically set by the system and can be used to gather system
information or control script behavior dynamically.
Options:-
Options in Linux are flags or parameters used to modify the behavior of commands. They
are usually prefixed by a single hyphen (-) for short options or double hyphen (--) for long
options.
Options help customize and control the execution of commands, making them more
flexible.
Shell/environment customization:-
Shell/Environment Customizations in Linux let you tailor the shell to your preferences
and improve efficiency. Key customizations include:
1. Prompt Customization (PS1): Modify the shell prompt to display user, host, or
directory info.
a. Example: PS1="\u@\h:\w\$ "
2. Aliases: Create shortcuts for commands.
a. Example: alias ll='ls -l'
3. Environment Variables: Set variables like PATH, EDITOR, and HISTSIZE for
personalized behavior.
a. Example: export EDITOR=vim
4. Configuration Files: Save customizations in .bashrc, .bash_profile, or .zshrc
for persistence.
5. Functions: Automate tasks with custom shell functions.
a. Example: function greet() { echo "Hello, $1!"; }
6. History Settings: Adjust command history size or behavior.
a. Example: export HISTSIZE=1000
7. Color Customization: Enable colored output for readability.
a. Example: alias ls='ls --color=auto'
8. Scripts: Automate setups with custom shell scripts.
These customizations optimize your workflow and make the shell more user-friendly.
Filters
• Filters are commands that take input (usually text), process it, and produce output.
They are often used to transform or analyze data.
• Examples of Filters:
o cat: Concatenates and displays file contents.
bash
Copy code
cat file.txt
o grep: Searches for patterns in text.
bash
Copy code
grep "pattern" file.txt
• Pipes (|) connect multiple commands, passing the output of one command as
input to another. This allows for chaining commands and creating complex
workflows.
• Syntax:
bash
Copy code
command1 | command2 | command3
• Examples:
o Find and count lines matching a pattern:
bash
Copy code
grep "error" log.txt | wc -l
• Filters become more powerful when combined with pipes to perform multi-step
data processing.
• Example: Analyze a log file for errors, sort them, and display the top 5:
bash
Copy code
grep "error" log.txt | sort | uniq -c | sort -nr | head -5
Summary
• Filters: Commands that process text (e.g., grep, sort, wc, awk).
• Pipes: Use | to pass output from one command to another.
• Filters and pipes together enable powerful and efficient data manipulation
workflows.
Concatenating file:-
oncatenating Files in Linux means joining or merging the contents of multiple files into
one, or displaying them together on the screen. The most common command for this is
cat, short for "concatenate."
bash
Copy code
cat file1.txt
bash
Copy code
cat file1.txt file2.txt
bash
Copy code
cat file1.txt file2.txt > merged.txt
bash
Copy code
cat file2.txt >> file1.txt
Advanced Options
bash
Copy code
paste file1.txt file2.txt
bash
Copy code
echo "New Content" >> file1.txt
Summary
1. Default Behavior:
a. Displays the first 10 lines of a file.
bash
Copy code
head file.txt
Summary
These commands are especially useful for file previews and log analysis.
The cut command extracts specific portions of a line or file, such as fields, columns, or
characters.
Usage
Examples:
The paste command joins lines from multiple files, typically side by side.
Usage
1. Default Behavior:
a. Joins corresponding lines from multiple files with a tab delimiter.
bash
Copy code
paste file1.txt file2.txt
Examples
bash
Copy code
cut -d',' -f1 file.csv > col1.txt
cut -d',' -f3 file.csv > col3.txt
paste col1.txt col3.txt
Summary
Both commands are versatile for processing text files, particularly for structured data.
Sorting:-
The sort command in Linux is used to arrange the lines of a text file or input in a specified
order, such as ascending or descending. It is versatile, allowing sorting by specific fields,
numerical values, or even custom criteria.
Basic Syntax
bash
Copy code
sort [options] [file]
bash
Copy code
sort file.txt
bash
Copy code
sort -r file.txt
1. Numerical Sorting:
a. Use the -n option to sort numbers instead of treating them as text.
bash
Copy code
sort -n file.txt
b. Example input:
Copy code
10
2
30
c. Output:
Copy code
2
10
30
b. Example input:
Copy code
Alice 30
Bob 25
Carol 20
3. Custom Delimiters:
a. Use the -t option to specify a delimiter.
bash
Copy code
sort -t',' -k2 file.csv
5. Unique Sorting:
a. Use the -u option to remove duplicate lines.
bash
Copy code
sort -u file.txt
6. Random Sorting:
a. Use the -R option to shuffle the lines randomly.
bash
Copy code
sort -R file.txt
7. Human-Readable Sorting:
a. Use the -h option for sizes like "2K," "1M," etc.
bash
Copy code
sort -h file.txt
Sorting Examples
bash
Copy code
sort names.txt
bash
Copy code
sort -t' ' -k1,3 log.txt
bash
Copy code
sort -n -r numbers.txt
bash
Copy code
sort -u file.txt
Summary
Translating characters: -
Translating Characters in Linux can be achieved using the tr command. This command is
used to replace, delete, or compress characters from standard input. It is particularly
useful for transforming data in files or pipelines.
Basic Syntax
bash
Copy code
tr [OPTIONS] SET1 [SET2]
• SET1: Specifies the characters to translate or manipulate.
• SET2: Specifies the characters to replace SET1 with.
Basic Usage
1. Replace Characters:
a. Replace all occurrences of one character with another.
bash
Copy code
echo "hello world" | tr 'h' 'H'
b. Output: xyzde
Common Options
b. Output: abc
3. Translate and Compress (-s):
a. Combine translation and compression in one command.
bash
Copy code
echo "aabbcc" | tr -s 'a-c' 'x-z'
b. Output: xyz
Character Classes
Class Description
[:lower
All lowercase letters
:]
[:upper
All uppercase letters
:]
[:digit
All numeric digits
:]
[:space Whitespace
:] characters
[:alnum Alphabetic and
:] numeric
Examples:
bash
Copy code
echo "hello world" | tr '[:lower:]' '[:upper:]'
bash
Copy code
echo "abc123xyz" | tr -d '[:digit:]'
a. Output: abcxyz
3. Replace Spaces with Hyphens:
bash
Copy code
echo "hello world" | tr '[:space:]' '-'
a. Output: hello-world
Advanced Examples
bash
Copy code
echo "hello@world#123!" | tr -cd '[:alnum:]'
a. Output: helloworld123
2. Replace Tabs with Spaces:
bash
Copy code
cat file.txt | tr '\t' ' '
bash
Copy code
echo "hello" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
a. Output: uryyb
Summary
Using uniq
The uniq command removes or processes duplicate lines in a file but works only on
adjacent duplicates. For non-adjacent duplicates, use sort first.
bash
Copy code
uniq file.txt
bash
Copy code
sort file.txt | uniq > unique_file.txt
bash
Copy code
sort file.txt | uniq -c
a. Output format:
Copy code
2 line1
3 line2
2. Sort by Frequency:
bash
Copy code
sort file.txt | uniq -c | sort -nr
bash
Copy code
sort file.txt | uniq -d
bash
Copy code
sort file.txt | uniq -c | awk '$1 > 1'
5. Examples
Copy code
apple
orange
banana
apple
orange
grape
1. Remove Duplicates:
bash
Copy code
sort file.txt | uniq
a. Output:
Copy code
apple
banana
grape
orange
2. Count Duplicates:
bash
Copy code
sort file.txt | uniq -c
a. Output:
Copy code
2 apple
1 banana
1 grape
2 orange
bash
Copy code
sort file.txt | uniq -d
a. Output:
Copy code
apple
orange
bash
Copy code
sort file.txt | uniq -u
a. Output:
Copy code
banana
grape
6. Automate with awk
bash
Copy code
awk 'seen[$0]++' file.txt
bash
Copy code
awk '!seen[$0]++' file.txt
Summary
Count characters:-
To count characters in files or input in Linux, you can use the wc (word count) command.
Here's how it works:
Basic Syntax
bash
Copy code
wc [OPTIONS] [FILE]
Counting Characters
b. Output:
Copy code
123 file.txt
bash
Copy code
echo "Hello, World!" | wc -m
a. Output:
Copy code
14
1. Count Bytes:
a. The -c option counts bytes instead of characters.
bash
Copy code
wc -c file.txt
b. Output:
Copy code
10 20 123 file.txt
Advanced Examples
bash
Copy code
wc -m file1.txt file2.txt
bash
Copy code
echo -n "Linux Rocks" | wc -m
bash
Copy code
awk '{ total += length } END { print total }' file.txt
Summary
Words or lines:-
To count words or lines in Linux, you can use the wc (word count) command. This
command provides counts for lines, words, characters, and bytes in files or input.
Basic Syntax
bash
Copy code
wc [OPTIONS] [FILE]
Counting Lines
bash
Copy code
echo -e "Hello\nWorld\nLinux" | wc -l
a. Output:
Copy code
3
Counting Words
b. Output:
Copy code
42 file.txt
bash
Copy code
echo "Hello, World! Linux is great." | wc -w
a. Output:
Copy code
5
Combining Counts
If you run wc without specific options, it shows counts for lines, words, and
bytes/characters.
bash
Copy code
wc file.txt
a. Output:
Copy code
15 42 256 file.txt
i. 15: Lines
ii. 42: Words
iii. 256: Characters (or bytes)
2. Count in Multiple Files:
bash
Copy code
wc file1.txt file2.txt
a. Output:
Copy code
12 30 200 file1.txt
15 42 256 file2.txt
27 72 456 total
Advanced Examples
bash
Copy code
grep -v '^$' file.txt | wc -w
1. Count Lines:
bash
Copy code
awk 'END { print NR }' file.txt
bash
Copy code
awk '{ total += NF } END { print total }' file.txt
Comparing files:-
To compare files in Linux, you can use different commands depending on the type of
comparison you need:
3. comm: Compare two sorted files, showing unique and common lines.
These tools help in comparing files or directories in different ways (line-by-line, byte-by-
byte, or based on checksums). Use the appropriate command depending on the
comparison type needed.