1. Introduction to VI Editor:

What is VI Editor?


VI is a screen editor used to edit files on a terminal.

It displays part of the file on the screen and allows the user to move the cursor to edit the file.

VI is one of the most popular text editors for UNIX systems.


How does it work?


VI displays a portion of the file on the screen. If the file is too large, the screen acts like a window into the file.

When you start VI, it opens a file in a buffer and shows the first part of the file.

If the file doesn't exist, VI will create a new one.


2. Modes in VI Editor:

VI has three main modes. It's important to understand which mode you're in because the commands behave differently in each.


Command Mode (Default Mode):


This is the mode where you can give commands like navigating, copying, cutting, or deleting text.

You start in this mode when you open VI.

To switch from Command Mode to Input Mode, press i, I, a, or A.

To enter Execute Mode, press :


Input or Insert Mode:


This mode is used to enter or edit text in the file.

To enter Input Mode, press i, I, a, or A while in Command Mode.

Press the Esc key to return to Command Mode.


Execute Mode:


This mode is used for saving changes, quitting VI, or searching for text.

To switch to Execute Mode, press : or / from Command Mode.


3. Switching Modes in VI:


From Command Mode to Input Mode:

Press i, I, a, or A to enter Input Mode.


From Input Mode to Command Mode:

Press Esc to return to Command Mode.


From Command Mode to Execute Mode:

Press : or / to enter Execute Mode.


4. Cursor Movement in VI Editor:


Using Arrow Keys:


Up Arrow: Moves the cursor up by one line.

Down Arrow: Moves the cursor down by one line.

Right Arrow: Moves the cursor right by one position.

Left Arrow: Moves the cursor left by one position.


Using H, J, K, L Keys (when arrows don’t work):


h: Move left.

j: Move down.

k: Move up.

l: Move right.


5. Screen Control Commands in Command Mode:


Ctrl + F: Move one screen forward.

Ctrl + B: Move one screen backward.

G: Move the cursor to the end of the file.

Num: Move the cursor to a specific line number (e.g., 10 to go to line 10).


6. Editing and Manipulating Text:


Deleting Text:

X: Delete the character under the cursor.

Dd: Delete the current line.


Copying Text:

Yy: Copy the current line.


Pasting Text:

P: Paste the copied line.


Undoing Changes:

U: Undo the last command.



7. Saving and Quitting VI:


To quit:

:q: Quit if no changes have been made.

:q!: Quit without saving changes.


To save:

:w: Save changes without quitting.


To save and quit:

:wq: Save changes and exit.


8. Special Keys for Mode Switching:


i: Switch from Command Mode to Input Mode.

Esc: Return to Command Mode from Input Mode.

:: Switch from Command Mode to Execute Mode.

/: Search for a string in the file.


Quick Tips:

Always start in Command Mode when you open VI.

Use Esc to leave Input Mode and go back to Command Mode.

Commands are case-sensitive (e.g., G is different from g).



1. Shell Keywords:

What is a Keyword?


A keyword is a word that has a special meaning in a specific programming language. In UNIX shell scripting, keywords are used to define certain operations like conditions, loops, etc.


Common Shell Keywords:


if: Used for decision-making (e.g., if statements).

for, while, until: Used for creating loops.

case: Used for multi-way branching (like switch in other languages).


These keywords have predefined meanings in the shell and cannot be used as variable names.


2. Shell Variables:

What is a Variable?


A variable in UNIX shell is a memory location that stores data.

You can assign values to variables and access them in your shell script.


Assigning Values:


Variables are usually assigned values using the = operator.

Accessing Variables: To access the value stored in a variable, you precede the variable name with a $ sign (e.g., $variable_name).


3. Types of Variables:


Predefined Variables:


These are system-defined variables that the shell uses internally. They include:

PS2: Secondary prompt string (default is >).

PATH: List of directories where the shell looks for commands.

HOME: User's home directory path.

LOGNAME: User's login name.

MAIL: Path to the mail file.

IFS: Internal field separator (default is space, tab, or newline).

SHELL: Pathname of the current shell.

TERM: Specifies the terminal type.

MAILCHECK: Frequency of mail checking.


User-Defined Variables:


You can define your own variables in shell scripts.

Naming Rules: Variables can consist of letters, digits, and underscores. They are case-sensitive (e.g., Var1 is different from var1).


4. User-Defined Variables (Commands):


set: Displays all variables and their values in the current shell.

unset: Removes the definition of a variable.

Example: unset HOME will remove the HOME variable.

echo: Used to print messages to the screen, or to display the value of a variable.

Example: echo $HOME will print the value of the HOME variable.


read: Reads input from the user during the script execution (similar to scanf in C).


Example:

echo "Enter your name: "

read name

echo "Hello, $name"

This will ask the user to input their name and then print a greeting.


5. Positional Parameters (Command-Line Arguments):


When running a shell script, arguments provided after the script name are called positional parameters. These arguments are stored in variables $1, $2, ..., $9, and the script can use them.

Example:

$ sh filename.sh first second third fourth ... ninth


The script would use:

$1 = "first"

$2 = "second"

$3 = "third"

and so on.


Special Positional Parameter:

$0: Stores the name of the script.

$#: Number of arguments passed to the script.

$@ or $*: All the arguments passed to the script.


6. Interactive Shell Script Using read and echo:


Adding User Interaction to Scripts: Sometimes you may want to prompt the user for input during the script execution. You can use echo to display a message, and read to capture user input.

Example 1: Simple Input/Output:

echo -n "Enter your name: "

read name

echo "Hello, $name"

This script prompts the user to enter their name, stores it in the variable name, and then greets the user.


Handling Different echo Behaviors Across Systems: Some UNIX systems use echo -n to avoid printing a newline at the end of the message, while others require echo message \c for the same result.

A solution that works across both systems:

if [ "`echo -n`" = "-n" ]; then

  n=""

  c="\c"

else

  n="-n"

  c=""

fi


echo $n "Enter your name: $c"

read name

echo "Hello, $name"


This script will ensure compatibility across systems, and produce the same output regardless of how the system's echo command behaves.


7. Key Commands Overview:

set: Lists all shell variables.

unset: Removes a variable definition.

echo: Prints a message or variable value to the screen.

read: Reads user input from the terminal.

Positional Parameters: $1, $2, ..., $9 to access arguments passed to the script.


Summary of Concepts:

Shell scripting provides ways to handle variables, keywords, and user input, making it a powerful tool for automating tasks.

Keywords have specific meanings in the shell, like if, for, while.

Variables are used to store data, with predefined variables offering system-related information and user-defined variables giving flexibility for custom storage.

Interactive Shell Scripts can use read and echo to communicate with the user and gather input.




3.8 Decision Statements (Making Choices)

In shell scripting, decision statements allow your script to make choices based on conditions.


1) if then fi (Simple Decision)

This is the simplest way to make decisions. It checks if a condition is true and then runs some code.


Syntax:

if [ CONDITION ]

then

    # Do something if CONDITION is true

fi


Example:

echo "Enter a number:"

read num

if [ $num -eq 5 ]

then

    echo "You entered 5."

fi


Explanation: If the user enters 5, it will print "You entered 5.".


2) if…then…else…fi (True or False Decision)

With this statement, if a condition is true, it runs one block of code. If it’s false, it runs another block of code.


Syntax:

if [ CONDITION ]

then

    # Code if CONDITION is true

else

    # Code if CONDITION is false

fi


Example:

echo "Enter a number:"

read num

if [ $num -gt 10 ]

then

    echo "The number is greater than 10."

else

    echo "The number is 10 or less."

fi


Explanation: It checks if the number is greater than 10. If it is, it prints "The number is greater than 10.", otherwise it prints "The number is 10 or less.".


3) if…then…elif…else…fi (Multiple Choices)

This is useful when you need to check multiple conditions. The script checks each condition until it finds one that’s true.


Syntax:

if [ CONDITION1 ]

then

    # Code if CONDITION1 is true

elif [ CONDITION2 ]

then

    # Code if CONDITION2 is true

else

    # Code if neither condition is true

fi


Example:

echo "Enter a number:"

read num

if [ $num -eq 0 ]

then

    echo "The number is zero."

elif [ $num -gt 0 ]

then

    echo "The number is positive."

else

    echo "The number is negative."

fi


Explanation: This checks if the number is 0, positive, or negative and prints the right message.


4) case…esac (Multiple Choices)

If you have many possible choices, you can use the case statement. It's cleaner and easier to manage than using many if statements.


Syntax:

case VARIABLE in

    pattern1)

        # Code for pattern1

        ;;

    pattern2)

        # Code for pattern2

        ;;

    *)

        # Default if no pattern matches

        ;;

esac


Example:

echo "Enter a number between 1 and 3:"

read num

case $num in

    1) echo "You entered 1.";;

    2) echo "You entered 2.";;

    3) echo "You entered 3.";;

    *) echo "Invalid input.";;

esac

Explanation: This checks if the input is 1, 2, or 3 and prints a message. If the input is anything else, it prints "Invalid input.".


2. Test Command (Checking Conditions)

The test command checks if a condition is true. It returns 0 (true) if the condition is true and 1 (false) if it's false.


Example:

echo "Enter a number:"

read num

if test $num -lt 5

then

    echo "The number is less than 5."

else

    echo "The number is 5 or more."

fi

Explanation: This checks if the number is less than 5. If true, it prints "The number is less than 5.".


3. Logical Operators (Combining Conditions)

You can combine multiple conditions using logical operators:


-a (AND): Both conditions must be true.


-o (OR): At least one condition must be true.


! (NOT): Reverses the condition.


Example:

a=5

b=10

if [ $a -lt 10 -a $b -gt 5 ]

then

    echo "Both conditions are true."

else

    echo "One or both conditions are false."

fi


Explanation: This checks if a is less than 10 and b is greater than 5.


4. Looping Statements (Repeating Code)

Sometimes you want to repeat code multiple times. Loops help you do that.


1) for Loop

This loop repeats a block of code for each item in a list.


Syntax:

for ITEM in LIST

do

    # Code to repeat

done


for i in 1 2 3 4 5

do

    echo "Number $i"

done


Explanation: This will print "Number 1", "Number 2", etc., until it reaches 5.


while Loop

This loop repeats code as long as a condition is true.


Syntax:

while [ CONDITION ]

do

    # Code to repeat

done


Example:

count=1

while [ $count -le 5 ]

do

    echo "Count is $count"

    count=$((count + 1))

done

Explanation: This will print the count and increment it until it reaches 5.


3) until Loop

This loop repeats code until the condition becomes true.


Syntax:

until [ CONDITION ]

do

    # Code to repeat

done


Example:

count=1

until [ $count -gt 5 ]

do

    echo "Count is $count"

    count=$((count + 1))

done


Explanation: This will print the count and increment it until it becomes greater than 5.



5. Arithmetic in Shell Script (Doing Math)

You can use basic math in shell scripts. Shell scripting supports arithmetic using operators like +, -, *, /, and %.


Example:

a=10

b=20


sum=$((a + b))

echo "Sum: $sum"


diff=$((a - b))

echo "Difference: $diff"


Explanation: This script adds and subtracts a and b, and prints the results.

Common Arithmetic Operators:


+: Add


-: Subtract


*: Multiply


/: Divide


%: Modulus (remainder of division)


Key Takeaways:

Decision Statements: Use if, case, and test to make decisions in scripts.


Loops: Use for, while, and until to repeat tasks.


Logical Operators: Combine conditions with -a (AND), -o (OR), and ! (NOT).


Arithmetic: Use basic math operators like +, -, *, /, and % in your scripts.




Unit-5:


3.12 What is Linux?

Linux is an operating system that connects a computer’s hardware to its software. It is used to manage and control hardware resources, like the CPU and memory, and allow programs to run on the computer.


Key Points:

Linux = Operating System (OS): Just like Windows or macOS, Linux helps run programs and manages hardware on a computer.

Not a Program: Linux is not a single program, but a system that controls how your computer and software interact.

Interface Between Hardware and Software: It acts as a bridge between the computer's physical parts (hardware) and the software you use (like browsers and games).


History of Linux:

Linus Torvalds: The creator of Linux, Linus Torvalds, was a student at the University of Helsinki. He was frustrated with a system called Minix and wanted to create a better operating system.


The Linux Kernel: Linus created the Linux kernel (the core part of the operating system), which grew into the full Linux operating system with help from developers worldwide.


Open Source: Unlike other operating systems, Linux is open-source, meaning anyone can modify, share, and use it for free.


Why is Linux Popular?

Free and Open-Source: You don’t have to pay for Linux, and anyone can make changes to it.


Customizable: You can change Linux to suit your needs.


Secure and Stable: Linux is known for being safe from viruses and very reliable, which is why it’s used in many servers.


Used Everywhere: From personal computers to smartphones (like Android), Linux is everywhere!


Summary:

Linux is an operating system created by Linus Torvalds.

It’s free, open-source, and highly customizable.

Linux is used in many devices and environments, including servers, computers, and smartphones.


GNU and GPL Concepts:


1. What is GNU?

GNU stands for "GNU's Not Unix". It is a free, UNIX-like operating system with no UNIX code.

It is free software and meant to be shared and modified by users.

Pronounced guh-noo, and is based on the GNU Hurd kernel.


2. What is GPL?

GPL stands for GNU General Public License.

It is a free software license that gives users the freedom to run, study, share, and modify software.

Written by Richard Stallman for the GNU Project.

Copyleft license: Any modified software must also be shared under the same GPL license.


Open Source and Freeware:


1. What is Open Source?

Open source means the software code is publicly available.

The copyright holder gives rights to study, modify, and redistribute the software for free and for any purpose.

Anyone can contribute to open-source projects and create new versions from existing software.


2. What is Freeware?

Freeware means software is available for free.

However, freeware comes with restricted rights and cannot be modified or redistributed freely.

In freeware, the development is usually done by a closed group, and the code is private.


Structure & Features of Linux:


1. Linux Architecture:

Linux architecture is composed of 4 main layers:


Hardware: The physical components of the system like Hard Disk, RAM, CPU, and Motherboard.


Kernel: The core component of the Linux operating system. It directly interacts with the hardware and manages system resources.


Shell: The interface between the user and the kernel. It takes input from users, sends instructions to the kernel, and returns the output from the kernel back to the user.


Applications: These are the programs that run on the Linux system, such as web browsers, media players, and text editors. They interact with the shell to execute tasks.


2. Features of Linux:

Portable: Linux software can work on different types of hardware platforms in the same way. Kernel and applications are adaptable to different systems.


Open Source: Linux is free and the source code is available to the public. It is a community-based development project that is constantly improving.


Multi-User: Linux is designed for multiple users to access system resources, like memory, RAM, and applications, at the same time.


Multiprogramming: Linux allows multiple applications to run simultaneously, enhancing efficiency.


Hierarchical File System: Linux uses a standard file structure to organize system and user files in a logical manner.


Shell: Linux provides an interpreter (Shell) to execute commands and manage system operations.


Security: Linux offers security features like password protection, file access control, and data encryption to ensure secure user interactions and system operations.


Installation and Configuration of Ubuntu Linux:


Step 1: Boot from the CD-ROM: Use a bootable Ubuntu CD.

Set the CD-ROM as the first boot device in the BIOS (press F2 or Delete).

The computer will boot from the CD and start the installation process. Press Enter to continue.


Step 2: Select Language: Choose your language (default is English).


Step 3: Keyboard Layout: The keyboard layout is usually auto-detected. Press Enter to confirm.


Step 4: Hardware and Network Detection: Ubuntu will automatically detect hardware and network connections.


If there are errors, you can skip network setup for now.


Step 5: Set Hostname: Choose a hostname for your computer (this is how your computer will be identified).


Step 6: Disk Partitioning: Choose how to partition your disk


Erase disk (default)

Resize existing partitions (if you need space for Ubuntu alongside other systems)

Manual partitioning if you want to set up custom partitions.


Step 7: Wait for Installation: Ubuntu will automatically copy required files and set up the system.


Step 8: Set Time Zone: Choose your time zone based on your location.


Step 9: Set Username and Password: Create a username and password to log in to the system.


Step 10: Install GRUB Boot Loader: If you have Windows installed, GRUB will allow you to choose between Ubuntu and Windows when starting the computer.


Step 11: Reboot: After installation, reboot your system to finish the setup.


Step 12: Wait for Final Installation: Ubuntu will install additional packages while you wait.


Step 13: Configure Monitor: Set the screen resolution according to your monitor's needs.


Step 14: First Boot: After rebooting, the Ubuntu login screen appears. Enter your username and password to log in.


Now you have Ubuntu installed and ready to use!


Startup, Shutdown, and Boot Loader in Linux


1. Shutdown in Linux: To shutdown your system, you can use the shutdown command.

If other users are logged in, it's polite to notify them before shutting down.

Command: shutdown [options] time [warning_message]

Example: To reboot immediately, you can use the following command:

shutdown -r now

This command will shut down or restart your system as specified.


2. Linux Boot Process: The Linux boot process refers to the series of steps that occur when starting your computer to load the operating system.

It involves several stages like hardware initialization, loading the boot loader, and finally, starting the operating system.


3. Boot Loader in Linux: The boot loader is responsible for loading the operating system into memory when the system starts.

In Ubuntu, the boot loader used is GRUB (Grand Unified Boot Loader).

How GRUB Works: When you start your computer, the GRUB boot loader appears.

If there is more than one operating system installed, GRUB lists them.

The default operating system will be automatically selected after a 10-second countdown.

You can also select a different OS if desired.

If you see an entry ending in "(recovery mode)", this is a safe mode that loads the system with minimal settings.


Linux Booting Process:


The Linux booting process is a series of 6 stages, also known as the start-up sequence. It begins when you press the power button and ends when the login screen appears.

1. BIOS (Basic Input/Output System)

Function: BIOS is the first program that runs when you turn on the computer.

It performs basic system checks (called POST, Power On Self Test) to ensure that the hardware is functioning properly.

Searches and loads the boot loader program from the hard drive to start the booting process.


2. MBR (Master Boot Record)

Location: The MBR is found in the first sector of the bootable disk (usually the hard drive).

Size: It's less than 512 bytes.

Function: The MBR is responsible for loading and executing the GRUB boot loader.


3. GRUB (Grand Unified Bootloader)

Function: GRUB is the bootloader used to load the operating system.

If multiple operating systems or kernel images are installed, GRUB lets you choose which one to boot.

Once selected, GRUB loads the kernel into memory to start the OS.


4. Kernel

Function: The kernel is the core part of the Linux operating system.

It mounts the root file system, as specified in the GRUB configuration file (grub.conf).

The kernel then starts the /sbin/init program to continue the boot process.


5. Init

Function: The init program looks at the /etc/inittab file to determine the Linux run level.


Run levels in Linux:


0 – Halt (shutdown)

1 – Single user mode (used for maintenance)

2 – Multi-user mode without NFS (Network File System)

3 – Full multi-user mode (command line)

4 – Unused (can be customized)

5 – Multi-user mode with X11 (Graphical user interface)

6 – Reboot (restart the system)


6. Run Level Programs

At this stage, the system starts various services and programs based on the selected run level.

You might see messages like "starting sendmail... OK" during boot-up.

These services are executed from the directories defined by the selected run level.


LILO Configuration

LILO (Linux Loader) is a boot loader used to boot the Linux operating system. It was once the default boot loader for many Linux distributions but has been largely replaced by GRUB in most modern distributions. However, LILO is still in use in many systems.


Key Configuration File:

LILO allows the user to select an operating system to boot, if more than one is installed.

The /etc/lilo.conf file is used to configure LILO settings.

After editing the configuration file, you must run the LILO command to update the boot loader.

The /etc/lilo.conf file is used to configure LILO.


Example of /etc/lilo.conf:

boot=/dev/hda          # Boot device (e.g., first hard drive)

map=/boot/map          # Location of map file

install=/boot/boot.b   # Where boot loader installs

prompt                 # Ask user to choose OS

timeout=50             # Time before default OS boots

message=/boot/message # Boot message file

lba32                  # Enable large disk support

default=linux          # Default OS to boot


Important Points:

boot=/dev/hda: Specifies the boot device.

prompt: Prompts user to choose the OS.

timeout=50: Time in seconds before default OS boots.

default=linux: Default OS to boot automatically.


Updating LILO:

After editing lilo.conf, run:

# lilo


This updates the boot loader.


GRUB Configuration


What is GRUB?


GRUB (Grand Unified Bootloader) is a boot loader that loads and starts the operating system when you turn on your computer. It can load multiple operating systems like Linux, Windows, etc.


Key Configuration File:

The configuration file for GRUB is located at /boot/grub/grub.conf.

Example of grub.conf:

default=0               # Specifies the default OS to boot

timeout=10              # Time in seconds before booting the default OS

splashimage=(hd0,0)/grub/splash.xpm.gz  # Background image for GRUB GUI


Explanation of Configuration Options:

default=0: Specifies the default boot option. 0 means the first OS listed in the GRUB menu.

timeout=10: GRUB will wait for 10 seconds before booting the default OS.

splashimage=: Path to an image file that GRUB uses as the background for its graphical interface.


Key Configuration Options:

default=0

Defines which operating system will be loaded by default.

0 means the first option in the boot menu.

timeout=10

Sets the time in seconds GRUB waits before loading the default OS.

10 seconds is the typical wait time.


splashimage=

Specifies the location of the image used as a background for the GRUB menu.


Creating Linux User Account and Password

Creating a User Account:

To create a new user in Ubuntu, follow these steps:


1. Command:

Use the adduser command to create a new user.

sudo adduser newusername


sudo: This allows you to run the command with administrative (superuser) privileges.

adduser: This command adds a new user to the system.

newusername: Replace this with the name of the new user.

2. Steps to Follow After Command:

Password: Type and confirm the password for the new user.

User Information: Enter user information (optional). Press Enter to use default values.

Confirmation: Press "Y" (or Enter) to confirm the information.

The new user account is now created on your system.


Deleting a User:

To delete a user, use the following command:

sudo userdel username


username: Replace this with the name of the user you want to delete.

Optional (Delete User's Home Directory): To remove the user's home directory as well, use:

sudo rm -rf /home/username


Explain Samba server in detail


Key Points:

GNU = Free UNIX-like OS.

GPL = Free software license ensuring users' rights to modify and share software.

Open Source: Code is available to all, allowing modification and redistribution.

Freeware: Available for free, but with limited rights and a closed development process.

Linux is a flexible, secure, and powerful operating system suitable for various users and platforms.

Shutdown: The shutdown command is used to safely turn off or reboot the system.

Boot Process: The boot process involves initializing hardware and loading the OS through a boot loader.

GRUB Boot Loader: GRUB is used to choose between multiple operating systems and to boot into recovery mode when needed.

BIOS: Initializes hardware and loads the boot loader.

MBR: Loads and executes the GRUB boot loader.

GRUB: Lets you select the kernel to boot.

Kernel: Mounts the root file system and starts init.

Init: Determines the run level and starts necessary services.

Run Level Programs: Services and programs start based on the run level.

LILO is configured via /etc/lilo.conf and must be updated with the lilo command after changes.

GRUB is used to load operating systems on your computer.

You can configure GRUB by editing the grub.conf file, where you set the default OS, the timeout, and even the background image.

It’s an essential tool for managing multiple operating systems on your machine.

Create a user: sudo adduser newusername

Delete a user: sudo userdel username

Delete home directory: sudo rm -rf /home/username