0% found this document useful (0 votes)
4 views22 pages

Unix Mod1pdf

The document provides an overview of the UNIX operating system, detailing its architecture, including the kernel and shell, and their roles in managing hardware and user interactions. It highlights key features such as multiuser support, multitasking, and the use of a toolkit of command-line utilities for various tasks. Additionally, it covers the flexibility of command usage, including combining and splitting commands for efficient operation.

Uploaded by

heyna2617
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)
4 views22 pages

Unix Mod1pdf

The document provides an overview of the UNIX operating system, detailing its architecture, including the kernel and shell, and their roles in managing hardware and user interactions. It highlights key features such as multiuser support, multitasking, and the use of a toolkit of command-line utilities for various tasks. Additionally, it covers the flexibility of command usage, including combining and splitting commands for efficient operation.

Uploaded by

heyna2617
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/ 22

• Operating System (OS)

• An operating system is software that controls the computer’s hardware and helps run programs safely and easily.

• >serves as an interface between applications and hardware resources, such as memory, storage devices (hard disks), and peripherals (printers). I
• it acts as a bridge between programs and hardware like memory, storage, and printers.
• The OS starts when the computer is turned on and works as long as the computer is running.

UNIX Operating System

• UNIX is a collection of programs that acts as a link between the user and the computer.

• It is the foundation for many operating systems like Ubuntu, Solaris, and POSIX.

• Developed in the 1970s by Ken Thompson, Dennis Ritchie, and others at AT&T Laboratories, it was originally written in assembly language but later rewritten in C.

• The core part of UNIX is the kernel, and users interact with it through a program called the shell.

• The shell is a command-line interpreter that works as an interface between the user and the system.

UNIX Architecture diagram from pdf ang go through the pdf once

1. Division of Labor

o Kernel:( he Kernel: Core of the Operating System

o The kernel is the main part of the operating system, written in C.

o It gets loaded into memory when the system starts and directly interacts with the hardware.

o Programs use the kernel’s services (called system calls) to access hardware.

o The kernel manages memory, schedules tasks, sets priorities, and handles many other background tasks.

o Even if no programs are running, the kernel keeps the system working.

o )

▪ The core of the operating system.

▪ Communicates directly with hardware.

▪ Manages memory, schedules processes, sets priorities, and performs essential tasks even when no user program is running.

▪ Written in C and loaded into memory during boot.

▪ Provides services to user programs via system calls.

Shell:( ommand Interpreter (Shell)

o The shell is the interface between the user and the kernel.

o Even though there's only one kernel, multiple users can have different shells running at the same time.

o $ echo $SHELL – Shows the current shell being used.

Different Shells

Bourne Shell ($)

o Developed by Steve Bourne at AT&T Labs.

o It's the oldest shell, but not commonly used today.

o Bash (Bourne Again Shell) is an enhanced version, widely used in Linux.

C Shell (%)

o Developed by Bill Joy at Berkeley.

o The name comes from its commands, which look like C programming language statements.

o tcsh is a compatible version used in Linux.

Korn Shell ($)

o Developed by David Korn at AT&T Labs.

o It's the newest and most powerful shell.

o It’s compatible with Bourne Shell.

System Prompt: For Bourne, Bash, and Korn shells, the prompt is usually a dollar sign ($).)

▪ Acts as a command interpreter between the user and the kernel.

▪ Translates user commands into kernel actions.

▪ Each user can have their own shell, even though only one kernel runs on the system.

▪ Types of shells:

▪ Bourne Shell (Sh): Simple and good for scripting.

▪ C Shell (Csh): Inspired by C programming, supports command history.

▪ Korn Shell (Ksh): Combines features of Sh and Csh, offering advanced scripting.

▪ Bash (Bourne Again Shell): Enhanced version of Sh, default in most Linux systems.

2. Files and Processes

o File:

▪ A collection of bytes, which can store text, images, or executable code.

▪ Files are organized hierarchically in the UNIX file system.

▪ Text files are dominant and can be manipulated with various tools.

o Process:

▪ A file becomes a process when executed.

▪ Represents a running instance of a program.

▪ Processes can be controlled (moved between foreground and background) with UNIX tools.
System Calls( System Calls in Unix

• The Unix system (including the kernel, shell, and applications) is written in C.

• System calls are functions used by commands to communicate with the kernel.

• For example, commands like write(), read(), open(), and close() are system calls that help the shell interact with files.

• The same system calls can be used for both files and devices.

• )

o Interface between user programs and the kernel.

o Allows programs to request hardware and OS services.

o Common system calls: read(), write(), open(), close().

o POSIX: A standard ensuring compatibility between UNIX-like systems by defining consistent system call interfaces.

o Examples:

▪ UNIX system calls: fork(), open(), chmod().

▪ Windows API equivalents: CreateProcess(), CreateFile(), SetFileSecurity().

Key Features

• File: "Files have places."

• Process: "Processes have life."

• Kernel-Shell Relationship: The kernel manages the hardware, and the shell serves as a user interface for executing commands.

Features of UNIX

1. Multiuser Support

o UNIX is a multiuser system, allowing multiple users to access the same computer system simultaneously.

o Resources like CPU, memory, and disk space are efficiently shared between users.

o Fair Resource Allocation: The system ensures that all users get an equal and fair share of resources without affecting overall performance.

o Useful in environments like servers, where many users may work on the same system.

2. Multitasking

o UNIX is a multitasking operating system, meaning it can run multiple tasks or processes at the same time.

o Process Scheduler: Manages how processes are executed, ensuring fair CPU time for each.

o Time-Sharing Mechanism: Divides CPU time among active processes to ensure responsiveness.

o Foreground and Background Processes:

▪ Foreground Processes: Run interactively and occupy the terminal.

▪ Background Processes: Run without user interaction, allowing the user to work on other tasks simultaneously.

▪ Example: Use & to run a process in the background (e.g., command &).

3. Building-Block Approach

o The building-block approach emphasizes simplicity and modularity.

o UNIX provides numerous small, simple commands, each designed for a specific task.

o Pipes (|): Connect commands to pass the output of one as the input to another, enabling the creation of complex workflows.

▪ Example: ls | wc lists files in a directory and then counts them.

o Benefits:

▪ Modularity: Small commands can be combined to handle complex tasks.

▪ Reusability: Commands can be reused in different workflows, making them versatile.

4. UNIX Toolkit

UNIX Toolkit

• A collection of small, flexible command-line tools for performing tasks like text manipulation, system administration, networking, and programming.

• Files, commands, and devices are treated uniformly, enabling seamless interaction between them.

o The UNIX toolkit refers to a collection of powerful and flexible command-line utilities.

o Tools include:

▪ General-Purpose Tools: Perform tasks like file editing (cat, vi), sorting (sort), and counting (wc).

▪ Text Manipulation Utilities: Such as grep (pattern searching), sed (stream editing), and awk (text processing).

▪ Compilers and Interpreters: For programming in languages like C, Python, etc.

▪ Networked Applications: Tools for networking like ftp, ssh, and curl.

▪ System Administration Tools: For managing users, processes, and file systems.

o Uniform Treatment of Files and Devices:

▪ In UNIX, files, commands, and devices are treated as files, enabling seamless interaction.

▪ Tools accept input from files, other commands, or standard input (keyboard).

5. Pattern Matching

o A powerful feature in UNIX for searching and manipulating text using regular expressions and metacharacters.

o Metacharacters: Special characters with unique meanings in pattern matching.

▪ Examples:

▪ .: Matches any single character except a newline.


▪ *: Matches zero or more occurrences of the preceding character.

▪ [ ]: Matches any one of the enclosed characters (e.g., [abc]).

o Regular Expressions: Define complex patterns to match specific sequences in text.

▪ Example: [a-zA-Z]\d{2} matches a letter followed by two digits.

o Tools like grep, sed, and awk use pattern matching extensively.

6. Programming Facility

Programming Facility

• The UNIX shell functions as a programming language with support for variables, loops, and control structures.

• Shell scripts allow automation of repetitive tasks by running a sequence of commands.

o The UNIX shell is not just a command interpreter but also a programming language.

o Features include:

▪ Control Structures: if, for, while, etc., for logic building.

▪ Variables: Allow storing and manipulating data.

▪ Shell Scripts: Scripts are text files containing sequences of UNIX commands.

▪ Automate repetitive tasks, making workflows more efficient and error-free.

▪ Example: A script to back up files.

o Flexibility: Users can combine commands and logic to create custom solutions.

7. Documentation

o UNIX offers comprehensive documentation for every command and system feature:

▪ Man Pages (Manual Pages): The primary source of documentation, offering detailed information on commands, system calls, libraries, etc.

▪ Access: Use man <command> (e.g., man ls).

▪ Info Pages: Provide more detailed documentation for some commands and topics.

▪ Access: Use info <command> (e.g., info ls).

▪ Help Options: Many commands include a --help option to display usage information.

▪ Example: ls --help.

o Importance: Documentation ensures that users can understand and utilize system features effectively.

UNIX Structure: The Kernel-Shell Relationship

The UNIX operating system is built on a layered architecture that provides a robust and efficient environment for multitasking, resource management, and user interaction. Here is a detailed breakdown of its key
components and their relationships:

1. The Kernel

The kernel is the core of the UNIX operating system. It is responsible for managing the system's resources and facilitating communication between hardware and software.

Key Functions

1. Process Control

o Manages the execution of processes, including:

▪ Multitasking: Allows multiple processes to run concurrently.

▪ Process Scheduling: Determines the order in which processes are executed, ensuring fair CPU allocation.

▪ Inter-Process Communication (IPC): Enables processes to share data and coordinate activities using mechanisms like pipes, message queues, and shared memory.

2. Resource Management

o Oversees the allocation and usage of system resources, such as:

▪ Memory Management: Allocates and deallocates memory for processes, ensuring efficient utilization.

▪ File System Management: Handles file operations like reading, writing, and organizing files in a hierarchical structure.

▪ Device Control: Manages interactions with hardware devices (e.g., printers, storage drives).

3. System Security

o Implements security measures to protect data and resources from unauthorized access.

Role in the System

The kernel is always active, working behind the scenes to ensure the system operates smoothly, even when no user programs are running. It is the foundation of all system operations, enabling communication between
hardware and software components.

2. The Shell

The shell is a command-line interpreter that serves as an interface between the user and the kernel. It translates user commands into system calls that the kernel can execute.

Key Functions

1. Interpreter

o Processes user input and translates commands into actions that the kernel performs.

o Example: When a user types ls, the shell translates it into a system call that retrieves the list of files in the directory.

2. Programming Capability

o The shell is also a powerful scripting environment, allowing users to write shell scripts.

▪ Shell Scripts: Text files containing sequences of commands and control structures (e.g., loops, conditionals).

▪ Scripts automate repetitive tasks, improve efficiency, and reduce errors.

o Popular shell types:


▪ Bourne Shell (sh): Basic shell with simple scripting capabilities.

▪ Bash (Bourne Again Shell): Enhanced version of Bourne Shell, widely used in Linux systems.

▪ C Shell (csh): Introduces syntax similar to the C programming language, with added features like command history.

▪ Korn Shell (ksh): Combines features of Bourne and C shells, offering enhanced scripting and performance.

3. Utilities

UNIX includes a wide range of utility programs that perform specialized tasks. These utilities work seamlessly with the shell to provide a powerful and flexible environment.

Categories of Utilities

1. Text Editors

o Tools for creating and modifying text files.

▪ Examples:

▪ vi: A modal editor with powerful text manipulation features.

▪ nano: A simple and user-friendly text editor.

2. Search Programs

o Tools for searching text within files using patterns or regular expressions.

▪ Example:

▪ grep: Searches for text patterns in files.

3. Sort Programs

o Utilities for organizing text data in a specific order.

▪ Example:

▪ sort: Sorts text lines alphabetically, numerically, or based on custom criteria.

4. System Administration Tools

o Utilities for managing the UNIX system, such as monitoring processes, managing users, and configuring settings.

▪ Examples:

▪ ps: Displays information about running processes.

▪ top: Provides a real-time view of system performance.

4. Applications

Applications are user-level programs designed for specific tasks. These are not part of the standard UNIX distribution but are built to extend the system’s capabilities.

Examples of Applications

1. Command-Line Tools

o Custom scripts or programs written by system administrators or users to automate tasks.

o Example: A backup script to copy files to a remote server.

2. Software Suites

o Advanced applications for development, data analysis, or other professional needs.

o Examples:

▪ Development tools like gcc (GNU Compiler Collection).

▪ Database systems like MySQL.

Relationship Between Kernel, Shell, and Utilities

The UNIX structure is a seamless integration of its components:

1. Kernel-Shell Interaction

o The shell translates user commands into system calls, which the kernel executes.

o Example: When a user requests to open a file, the shell communicates with the kernel using the open() system call.

2. Utilities and Shell

o Utilities enhance the functionality of the shell by providing tools to perform specific tasks.

o Example: Combining utilities with pipes to create complex workflows (e.g., grep 'pattern' file | sort).

3. Applications and Kernel

o Applications interact indirectly with the kernel through system calls, often mediated by the shell or utility programs.

Summary Figure

The UNIX architecture can be visualized as:

• Core (Kernel): Manages resources and handles low-level operations.

• Middle Layer (Shell): Interfaces between users and the kernel, with scripting and command interpretation capabilities.

• Outer Layer (Utilities & Applications): Tools and programs that perform specific tasks, enhancing the system’s usability.

This layered structure ensures flexibility, efficiency, and the modularity that UNIX is known for.
Flexibility of Command Usage in UNIX

UNIX provides great flexibility in using commands, allowing users to work efficiently by combining, splitting, or managing commands in various ways. Here's a detailed explanation in simple terms:

1) Combining Commands

You can run multiple commands in one line by separating them with a semicolon (;). This lets you execute several tasks sequentially without needing to re-enter each command.

Example:

ls; mkdir new_directory; cd new_directory

• Explanation:

1. ls: Lists the files in the current directory.

2. mkdir new_directory: Creates a new directory called new_directory.

3. cd new_directory: Moves into the newly created directory.


These commands run one after the other automatically.

You can also group multiple commands using parentheses and redirect their combined output to a file.

Example:

(date; ls -l testdir) > newlist

• Explanation:

o date: Displays the current date and time.

o ls -l testdir: Lists the contents of the directory testdir in detailed format.

o The combined output of both commands is saved in the file newlist.

2) Splitting Commands Across Multiple Lines

If a command is too long or needs to be spread out for better readability, UNIX allows you to split it across multiple lines. The shell provides a secondary prompt (>) to indicate the command is incomplete.

Example:

echo "This is

>a multiline text"

• Explanation:

o The command is written in two lines but treated as one logical line.

o The output will be:


This is a multiline text.

Long commands that exceed the terminal's width can also overflow naturally, continuing on the next line, while remaining one logical line.

3) Entering Commands While Another is Running

UNIX allows you to type new commands while another long-running program is still executing. These new commands are stored in a buffer (temporary storage) by the kernel. Once the running program finishes, the new
commands are processed.

Example:

$sleep 10

date; cal

• Explanation:

1. sleep 10: Pauses execution for 10 seconds.

2. While waiting, you can type the next commands:


date; cal.

3. Once the 10 seconds pass, the date command runs (showing the current date and time), followed by cal (displaying the calendar).

Conclusion

These features make UNIX highly flexible:

• Combine commands to save time.

• Split commands across lines for clarity.

• Enter new commands while waiting for others to complete.

This flexibility empowers users to handle tasks efficiently, even in complex scenarios.

Internal Commands • Internal commands in Unix/Linux are commands that are built into the shell itself. They are directly executed by the shell without requiring an external executable file. This results in faster execution
because the shell doesn't need to search the file system for the command.

Internal commands are an integral part of the shell and are always available to users, even if the shell is running in minimal environments, such as a recovery or rescue mode.

Key Internal Commands

1. cd (Change Directory)

• Purpose: The cd command changes the current working directory of the shell.

• How it works: The cd command changes the current directory, which is used by the shell to determine the context for file operations (like file creation, editing, etc.). The shell internally keeps track of the current
directory and updates it whenever you use cd.
• Syntax:

cd [directory]

o directory: The path to the directory you want to move to. If not provided, it moves to the home directory by default.

• Example:

$ cd /home/user

This will change the current directory to /home/user.

$ cd ..

This command moves one level up in the directory hierarchy.

• Key Points:

o cd does not return any output if it successfully changes the directory.

2. echo (Print to Terminal)

• Purpose: The echo command is used to display a message or the value of a variable to the terminal. It is one of the most frequently used commands for debugging or displaying output in shell scripts.

• How it works: echo writes its arguments to standard output, usually the terminal. It can print simple strings, or if variables are passed, it will print the value of the variables.

• Syntax:

echo [options] [string]

o options: You can use flags like -n (to avoid newline at the end) or -e (to interpret backslash escapes).

o string: The text or variable whose value is to be displayed.

• Example:

$ echo "Hello, Unix!"

Hello, Unix!

This will print Hello, Unix! to the terminal.

$ echo $HOME

/home/user

This will print the value of the $HOME environment variable, which is the current user's home directory.

• Key Points:

o echo can be used to display simple strings or the contents of variables.

o The command does not modify system state or environment; it’s just for output.

pwd (Print Working Directory)

• Purpose: The pwd command displays the absolute path of the current working directory, showing where you are in the filesystem.

• How it works: The shell internally tracks the current working directory. When you invoke pwd, it simply returns the path of the directory the shell is currently working in.

• Syntax:

pwd

• Example:

$ pwd

/home/user

This will display /home/user if that's the current directory.

• Key Points:

o pwd is very useful in shell scripting or when working with complex directory structures to know exactly where you are.

o The command does not change the system state; it is read-only.

4. exit (Exit the Shell)

• Purpose: The exit command is used to terminate the current shell session, effectively closing the terminal window or ending the script.

• How it works: When you invoke exit, the shell session is terminated. In the case of a script, it will stop executing the script at that point.

• Syntax:

exit [status]

o status: (optional) An exit status code (an integer). By convention, an exit status of 0 indicates success, and any non-zero value indicates an error.

• Example:

$ exit

This will close the terminal or logout from the current session.

$ exit 1

This will exit the shell and return the status code 1, indicating an error or abnormal termination.

• Key Points:

o Useful when you want to terminate a script or session.

o Exiting with status 0 means the session or script ended successfully.

Advantages of Internal Commands

1. Speed: Since internal commands do not require an external process to be launched, they are typically faster than external commands.

2. No External Files: These commands do not rely on separate executables, making them available in all environments, even if only the shell is installed.

3. Simplicity: Internal commands are part of the shell, so users don't have to worry about paths, dependencies, or separate executable files.

4. Availability: These commands are always available as long as the shell is running.

Summary
Internal commands are fundamental to shell operation and provide essential functionality for navigation, output display, and session control. They are directly implemented within the shell and are critical for interacting
with the system efficiently, especially for tasks like changing directories, displaying information, and terminating sessions. Understanding these commands is key to mastering shell scripting and Unix/Linux systems.

. cd (Change Directory)

Purpose: Detailed Explanation of cd (Change Directory)

The cd (Change Directory) command is one of the most fundamental and frequently used commands in Unix/Linux shells. It allows the user to navigate between directories within the file system.

Purpose:

The primary purpose of the cd command is to change the current working directory of the shell. The shell keeps track of the current directory, and when the cd command is used, it updates the shell’s reference to that new
directory.

Commands and Outputs

1. Change to a specific directory:

• Command:

cd /home/user

• Output: (No output, just changes the directory.)

The command changes the current working directory to /home/user. After this, any relative paths used in the shell will be relative to /home/user. For example, using ls will list the contents of /home/user.

2. Move to the parent directory:

• Command:

cd ..

• Output: (No output, moves to the parent directory.)

The .. represents the parent directory of the current directory. When you use cd .., it moves the current working directory up one level. For instance, if you are in /home/user/docs, executing cd .. will change the directory to
/home/user.

3. Go to the home directory:

• Command:

cd

• Output: (No output, changes to the home directory.)

When you use the cd command with no arguments, it automatically takes you to your home directory. The home directory is usually represented by the environment variable $HOME. For example, if your username is
"user," and your home directory is /home/user, using cd without arguments will take you there.

Additional Notes:

• No Output on Success: The cd command does not typically produce any output if it successfully changes the directory.

• Error on Failure: If you try to cd into a directory that does not exist, you will receive an error message,

• Use with Absolute or Relative Paths:

o Absolute paths begin from the root directory (/). For example, cd /var/log.

o Relative paths begin from the current directory. For example, cd docs (if there's a docs directory in the current directory).

Key Points:

• Shortcut: cd ~ will also take you to the home directory.

• Navigation: cd - will take you back to the previous directory you were in.

2. echo (Print Text to the Terminal)

Purpose: echo Command in Unix/Linux

The echo command is used to print text, variables, or the output of commands to the terminal. It’s one of the most commonly used commands for output in shell scripts and terminal usage.

Purpose of echo:

The echo command prints its arguments to the standard output (usually the terminal). It is often used to display text, the contents of variables, and formatted output, as well as to show results from executing other
commands.

Basic Usage and Commands:

1. Print a Simple Message:

• Command:

echo "Hello, Unix!"

• Description: This prints the string Hello, Unix! to the terminal.

• Output:

Hello, Unix!

2. Display the Value of a Variable:

• Command:

NAME="Alice"

echo "Hello, $NAME!"

• Description: This prints the value of the variable NAME (Alice) to the terminal. You can use variables inside strings by referencing them with $.

• Output:

Copy code

Hello, Alice!

3. Use Escape Sequences:


• Command:

bash

Copy code

echo -e "Line 1\nLine 2"

• Description: The -e option enables interpretation of escape sequences. Here, \n creates a newline, so the output is displayed on two lines.

• Output:

Line 1

Line 2

Common Escape Sequences in echo:

• \n: Newline (moves the output to the next line).

• \t: Tab (adds a tab space).

• \\: Backslash (prints a single backslash).

• \": Double quote (prints a double quote).

• \b: Backspace (moves one character back).

• \r: Carriage return (moves the cursor to the beginning of the line).

The echo command can also be used to output to files by redirecting its output using the > or >> operators.

Example:

echo "Hello, World!" > file.txt

This writes Hello, World! to the file file.txt.

3. pwd (Print Working Directory)

Purpose: pwd Command in Unix/Linux

The pwd command stands for Print Working Directory. It is used to display the full path of the current working directory in the filesystem. This is useful when you want to know where you are in the filesystem or confirm
your location after navigating with the cd command.

Purpose of pwd:

The pwd command shows the absolute path of the current directory you're working in. This path starts from the root directory (/) and includes all directories leading to the current directory.

Basic Usage and Commands:

1. Show the Current Directory:

• Command:

bash

Copy code

pwd

• Description: This prints the full path of the directory you are currently in.

• Output:

arduino

Copy code

/home/user

This output indicates that the current directory is /home/user.

2. After Changing Directory:

• Command:

bash

Copy code

cd /var/log

pwd

• Description: After changing the directory using cd, the pwd command will show the new directory path.

• Output:

bash

Copy code

/var/log

This shows that the current directory has been changed to /var/log.
Additional Notes:

• The output of pwd is always an absolute path, starting from the root (/) of the filesystem.

• It does not take any arguments for specific paths, as it only works to show the path of the current directory.

Summary of pwd Co

4. exit (Exit the Shell)

Purpose: exit Command in Unix/Linux

The exit command is used to terminate the current shell session. When you use this command, the shell will close, and you will return to the previous level (e.g., the terminal window or login session). It is often used when
you are finished with your work in a shell session.

Purpose of exit:

The exit command is used to end a shell session and close the terminal window or the current shell. Additionally, you can specify an exit code to indicate the status of the session or program (commonly used for scripting or
indicating error states).

Basic Usage and Commands:

1. Exit the Shell (Normal Termination):

• Command:

bash

Copy code

exit

• Description: This will close the current shell session and return to the terminal or logout.

• Output: (No output; it simply closes the session.)

2. Exit the Shell with an Error Code:

• Command:

bash

Copy code

exit 1

• Description: This closes the shell session and returns an exit code 1, which is often used to indicate an error or abnormal termination.

• Output: (No output; the session is closed, and the exit status is set to 1.)

Exit Codes:

Exit codes are useful for scripts or commands where you want to communicate the status of the session or command. The general convention is:

• Exit code 0: Successful completion or normal termination.

• Exit code 1 or any non-zero value: An error occurred, or abnormal termination.

For example:

• exit 0: Indicates success (often used in scripts).

• exit 1: Indicates failure or some error (commonly used for debugging or error handling).

External Commands • These commands are not built into the shell.
They exist as separate executable files in the file system.

• The shell locates these commands in directories specified by the PATH variable and then executes them.

• Examples: ls, cat, grep, find.

• Slightly slower compared to internal commands because the shell needs to find and execute the corresponding file.

• If a command has entry in built-in set and has external file also, in such situation internal command takes precedence.

External commands in Unix/Linux are not built into the shell itself but exist as separate executable files stored on the system. These commands are located in directories specified by the PATH environment variable, and
when invoked, the shell searches for and executes these files. While these commands offer additional functionality, they can be slightly slower than internal commands because the shell has to search for the executable file
and launch it.

Key Characteristics of External Commands:

1. Separate Executable Files: Unlike internal commands (which are built into the shell), external commands are individual files found on the filesystem. These files can be programs or scripts.

2. Location in Directories: The shell searches for external commands in the directories listed in the PATH environment variable. The directories in PATH are a set of locations where executable files are stored, and
the shell looks through these directories when you enter a command.

3. Slower Execution: Since the shell needs to find and execute the corresponding file, external commands can be slightly slower compared to internal commands that are executed directly by the shell without
needing an external executable.

4. Precedence: If a command exists as both an internal and external command (i.e., a built-in shell function and an executable file with the same name), the internal command will take precedence over the external
one. The shell will execute the built-in version instead of searching for the external executable.

ls (List Directory Contents)

ls Command (List Directory Contents) in Unix/Linux


The ls command is used to list the contents of a directory in Unix/Linux systems. It is one of the most frequently used commands for navigating and exploring the file system.

Basic Usage:
1. List files and directories in the current directory:
1. Basic Command
• Command: ls
• What it does: Displays the names of files and directories in the current working directory.
• Example Output:
Copy code
file1.txt file2.txt dir1 dir2

2. List All Files, Including Hidden Files


• Command: ls -a
• What it does: Lists all files, including hidden files (files that start with a dot .).
Hidden files are often configuration files.
• Example Output:
Copy code
.hiddenfile file1.txt file2.txt dir1
• Key Point: The -a option reveals hidden files.

3. Long Listing Format


• Command: ls -l
• What it does: Displays detailed information about each file and directory.
• Example Output:
sql
Copy code
-rw-r--r-- 1 user group 1024 Dec 14 10:00 file1.txt
drwxr-xr-x 2 user group 4096 Dec 14 09:00 dir1
• Explanation of Each Column:
1. -rw-r--r--: File permissions
▪ - (regular file), d (directory).
▪ rw- means the owner has read and write permission.
▪ r-- means the group and others have read-only permission.
2. 1: Number of hard links to the file.
3. user: The owner of the file.
4. group: The group associated with the file.
5. 1024: File size in bytes.
6. Dec 14 10:00: The last modified date and time.
7. file1.txt: The name of the file.

4. Sort Files by Size


• Command: ls -lS
• What it does: Displays files in detailed format, sorted by size (largest first).
• Example Output:
-rw-r--r-- 1 user group 2048 Dec 14 10:00 file2.txt
-rw-r--r-- 1 user group 1024 Dec 14 10:00 file1.txt
• Key Point: The -S option sorts files by size, and combining it with -l provides detailed information.

5. Recursive Listing
• Command: ls -R
• What it does: Displays all files and directories, including the contents of subdirectories.
• Example Output:
file1.txt dir1

dir1:
subfile1.txt
• Key Point: The -R option shows the contents of subdirectories, making it useful for exploring nested files.

6. Human-Readable File Sizes


• Command: ls -lh
• What it does: Displays file sizes in human-readable formats like KB, MB, or GB.
• Example Output:
csharp
Copy code
-rw-r--r-- 1 user group 1.0K Dec 14 10:00 file1.txt
• Key Point: The -h option converts file sizes to a more understandable format.

7. Color-Coded Output
• Command: ls --color
• What it does: Adds colors to the output for better identification.
o For example:
▪ Directories might appear in blue.
▪ Executable files might appear in green.
• Key Point: This makes it easier to distinguish between different types of files.

8. Sort Files by Modification Time


• Command: ls -lt
• What it does: Displays files sorted by their last modification time, with the most recently modified files first.
• Example Output:
csharp
Copy code
-rw-r--r-- 1 user group 1024 Jan 01 12:00 file1.txt
-rw-r--r-- 1 user group 2048 Dec 31 23:00 file2.txt
• Key Point: The -t option sorts files by time.

Combining Options
You can combine multiple options for more powerful results:
• Command: ls -alh
o Lists all files, including hidden ones, in a detailed format with human-readable file sizes.
• Command: ls -ltR
o Lists files recursively, sorted by modification time.
Summary of Key Options
Option Description
-a Show all files, including hidden files.
-l Long listing format with detailed file info.
-S Sort files by size.
-R List files and subdirectories recursively.
-h Display human-readable file sizes.
--color Add color-coded output for better visualization.
-t Sort files by modification time.

Summary:
The ls command is a versatile tool for displaying files and directories in Unix/Linux systems. By using different options, you can customize the output to show detailed information, hidden files, file sizes, and even
recursively list contents of subdirectories. It is fundamental for navigating the filesystem and inspecting directory contents efficiently.

*cat (Concatenate and Display File Content)


cat Command (Concatenate and Display File Content) in Unix/Linux
The cat command is one of the most commonly used commands in Unix/Linux. It stands for "concatenate" and is used to display the contents of files, combine multiple files into one, and even create or modify
files.

Common Scenarios and Examples:


1. Display file content:
o Command:
bash
Copy code
cat file1.txt
o Output:
csharp
Copy code
This is the content of file1.txt.
o Explanation: Displays the contents of file1.txt directly in the terminal.
2. Combine two files into a new file:
o Command:
bash
Copy code
cat file1.txt file2.txt > combined.txt
o Effect: This combines the contents of file1.txt and file2.txt into a new file combined.txt.
o Explanation: The > operator redirects the output to combined.txt, overwriting it if the file exists.
3. Display with line numbers:
o Command:
bash
Copy code
cat -n file1.txt
o Output:
arduino
Copy code
1 This is line 1.
2 This is line 2.
o Explanation: The -n option adds line numbers to the output.
4. Create a new file:
o Command:
bash
Copy code
cat > newfile.txt
o Input:
csharp
Copy code
This is the new content.
o Effect: Creates a new file named newfile.txt and allows the user to input content. To save and exit, press Ctrl+D.
o Explanation: The > operator creates a new file (or overwrites it if it exists) and writes the entered content into it.
5. Append to an existing file:
o Command:
bash
Copy code
cat >> file1.txt
o Input:
css
Copy code
Additional content.
o Effect: Appends the new content to the end of file1.txt.
o Explanation: The >> operator appends the content to the existing file rather than overwriting it.
Additional Useful Options for cat:
• Show non-printing characters:
o Command:
bash
Copy code
cat -v file1.txt
o Explanation: This shows non-printing characters (such as control characters) in the output.
• Display file content with trailing newlines:
o Command:
bash
Copy code
cat -E file1.txt
o Explanation: The -E option shows $ at the end of each line, making it easier to see line endings.
• Concatenate multiple files and show their content:
o Command:
bash
Copy code
cat file1.txt file2.txt
o Explanation: This will display the contents of file1.txt followed by the contents of file2.txt sequentially.
Summary:
The cat command is a versatile tool in Unix/Linux for displaying, combining, and creating files. It is particularly useful for quickly viewing file contents, combining files into one, or creating new files with specific
content. By using various options, such as -n for line numbers and -E for trailing newlines, you can tailor the output to meet your needs.

Command Arguments and Options in UNIX


Definition:
• Command: A program or utility executed in UNIX (e.g., ls, echo, cat, find).
• Arguments: These specify what the command will act upon, like filenames, directories, or text.
• Options: These modify or extend the behavior of a command. Options usually begin with a - or --.
General Syntax:
command [options] [arguments]
• command: The utility you want to execute (e.g., ls, cat).
• [options]: Flags that alter how the command behaves (e.g., -a, -l).
• [arguments]: Inputs to the command (e.g., file names, text).

Command Arguments and Options in UNIX


In UNIX and Linux, commands are used to perform specific tasks. These commands can be customized using arguments and options to modify their behavior. Understanding how to use commands, arguments, and options
together is essential for effective usage of the shell.

Definitions:
• Command: A program or utility executed in UNIX (e.g., ls, echo, cat, find).
• Arguments: These specify the targets or objects the command will operate on, such as filenames, directories, or text. For example, in the command ls /home/user, /home/user is an argument.
• Options: These modify or extend the behavior of a command. Options usually begin with a - (single hyphen) or -- (double hyphen). For example, in the command ls -l, -l is an option that provides a long listing of
files.

General Syntax:
The general syntax for UNIX commands follows this structure:
bash
Copy code
command [options] [arguments]
• command: The utility or program you want to execute (e.g., ls, cat).
• [options]: Flags or switches that alter how the command behaves (e.g., -a, -l).
• [arguments]: Inputs or targets the command operates on, such as file names or directories (e.g., file1.txt, /home/user).
Examples:

Examples of Commands with Arguments and Options


Nn 1. ls (List Directory Contents):

• Command: ls
o Lists files and directories in the current directory.
o No arguments: ls
o With arguments: ls /home/user
• Options:
o -a: List all files, including hidden ones (those starting with a dot .).
bash
Copy code
ls -a
o -l: Use long listing format, showing detailed information (permissions, owner, size, date, etc.).
bash
Copy code
ls -l
o -lh: Combine options to show file sizes in a human-readable format.
bash
Copy code
ls -lh
2. echo (Print Text to the Terminal):
• Command: echo
o Prints a text message or variable to the terminal.
o With arguments:
bash
Copy code
echo "Hello, world!"
• Options:
o -n: Prevents the newline character at the end of the output.
bash
Copy code
echo -n "Hello, world!"
3. cat (Concatenate and Display File Content):
• Command: cat
o Displays the contents of one or more files.
o With arguments:
bash
Copy code
cat file1.txt
• Options:
o -n: Displays line numbers along with the file content.
bash
Copy code
cat -n file1.txt
o -b: Displays line numbers but skips empty lines.
bash
Copy code
cat -b file1.txt
4. find (Search for Files and Directories):
• Command: find
o Searches for files and directories within a directory hierarchy.
o With arguments:
bash
Copy code
find /home/user -name "*.txt"
• Options:
o -name: Searches for files by name.
o -type: Specifies the type of file (e.g., f for regular files, d for directories).
bash
Copy code
find /home/user -type f
o -exec: Executes a command on the found files.
bash
Copy code
find /home/user -name "*.txt" -exec cat {} \;

Types of Options:
1. Short Options:
o These options usually have a single character, prefixed with a single hyphen (-).
o Example: -a, -l, -n
Example:
bash
Copy code
ls -al
o This command combines -a and -l to list all files in the long format.
2. Long Options:
o These options are more descriptive and are prefixed with two hyphens (--).
o Example: --all, --long, --help
Example:
bash
Copy code
ls --all --long
3. Combined Options:
o Some commands allow combining short options after a single hyphen.
o Example: ls -al, where -a and -l are combined together.
Conclusion:
In UNIX/Linux, commands can be customized and made more powerful by using various arguments and options. Arguments specify what the command acts upon (like files or directories), and options modify the behavior
of the command (like how output is formatted). Understanding how to structure commands with these components helps in performing complex tasks efficiently.

1. ls Command (List Files and Directories)


The ls command lists the contents of a directory.
1. Basic Command:
ls
Output:
file1.txt file2.txt dir1 dir2
o No options or arguments: Lists files and directories in the current directory.
2. Using Options:
ls -l
Output:
-rw-r--r-- 1 user group 1024 Dec 14 12:00 file1.txt
drwxr-xr-x 2 user group 4096 Dec 14 12:00 dir1
o Option -l: Displays detailed information (permissions, owner, size, etc.).
3. With Arguments (Specify a Directory):
ls dir1
Output:
subfile1.txt subfile2.txt
o Argument dir1: Specifies the directory to list files from.
4. Combining Options and Arguments:
ls -lh dir1
Output:
-rw-r--r-- 1 user group 1.0K Dec 14 12:00 subfile1.txt
o Option -h: Displays file sizes in human-readable format (e.g., KB, MB).
o Argument dir1: Target directory.

2. cat Command (Concatenate and Display File Content)


The cat command reads and displays the content of files.
1. Basic Command:
cat file1.txt
Output:
This is the content of file1.txt.
o Argument file1.txt: Specifies the file to display.
2. With Multiple Arguments:
cat file1.txt file2.txt
Output:
This is the content of file1.txt.
This is the content of file2.txt.
o Arguments file1.txt and file2.txt: Combine and display content of both files.
3. Using Options:
cat -n file1.txt
Output:
1 This is the content of file1.txt.
o Option -n: Adds line numbers to each line of the file.
4. Create a New File (Using Redirection):
cat > newfile.txt
Input:
This is a new file. (Press Ctrl+D to save)
o Effect: Creates newfile.txt with the entered content.

echo Command (Display Text or Variables)


The echo command prints text or variables to the screen.
1. Basic Command:
echo "Hello, World!"
Output:
Hello, World!
o Argument "Hello, World!": Text to display.
2. Display a Variable:
name="Alice"
echo "Hello, $name!"
Output:
Hello, Alice!
o Option $name: Refers to the variable name.
3. Escape Characters:
echo -e "Line1\nLine2"
Output:
Line1
Line2
o Option -e: Enables interpretation of escape sequences like \n (newline).
4. Redirect Output to a File:
echo "This is some text" > file1.txt
o Effect: Writes "This is some text" to file1.txt.
5. Append Text to a File:
echo "Additional text" >> file1.txt
o Effect: Appends "Additional text" to file1.txt.
Conclusion
• Arguments specify the input to commands. Examples:
o File names (file1.txt, dir1).
o Patterns ("*.txt", "file1").
o Text ("Hello, World!").
• Options modify the behavior of commands. Examples:
o ls -l: Detailed file listing.
o cat -n: Show line numbers.
o find -name: Search by file name.

By combining options and arguments, UNIX commands become highly flexible and powerful.
• Use Spacebar or Enter to move forward.
• Press q to quit the manual page.

Navigating Manual Pages:


1. Forward Scrolling: Use Spacebar or Enter to move down one screen or line.
2. Backward Scrolling: Use b (only works with less as the pager).
3. Search: Press /, then type a keyword and hit Enter. Use n to move to the next match.

Commands: Navigation in man command


• Spacebar: Move forward one page.
• b: Move backward one page.
• ↑/↓: Scroll one line up or down.
• /: Start a forward search (e.g., /OPTIONS).
• n: Jump to the next occurrence of the search term.
• q: Exit the man page.

You can explore its own manual page by typing man man, which will explain the syntax and usage of the man command itself.
root Account in UNIX:
In UNIX, the root account is the superuser with full administrative privileges, capable of performing any action on the system. Similar to Linux, the root user can:
• Modify system files.
• Install and manage software.
• Manage users and groups.
• Perform system-level maintenance tasks.
Logging into the Root Account in UNIX:
• Login Name: root
• Password: The root user has a dedicated password.
The root account is commonly used for system administration and troubleshooting. However, it is recommended to avoid using root for day-to-day tasks for security reasons.

exolain 4 file related commands


Scprit command I detail

You might also like