0% found this document useful (0 votes)
16 views

Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 98

Notes

The Linux Operating System (OS) is a popular open-


source operating system that is widely used for servers,
desktops, and mobile devices. It was developed by Linus
Torvalds in 1991 and combined with GNU in 1992 to form a
completely free operating system1. The Linux OS is known
for its stability, security, and flexibility, and it supports
various shells such as Bash, Korn, C, Tcsh, and Z1.
The Linux OS is responsible for managing computer
hardware and system resources, including memory and
hard disks, and it forms the base on which application
software is developed. It performs several functions, such
as command interpretation, process management,
memory management, input/output operations, and file
management. The Linux OS also supports
multiprogramming, time-sharing, and multitasking.
In terms of security, the Linux OS uses file access
permissions (FAPs) associated with the type of users.
There are three types of permissions Read (r), Write (w),
and Execute (x). These permissions can be changed using
the chmod command, which allows users to grant or
remove permissions for different users (u, g, o, and a).

The Linux Shell is a command-line interface that interacts


with the Linux operating system. It provides a way to
execute various commands and manage files and
directories. Here are some of the commands and topics
you can find in the Linux Shell

Here are the notes for each command and topic in the
provided Linux Shell file

1. **Managing Disk Files and Directories** This section


covers basic commands for managing files and
directories, such as `ls`, `pwd`, `cd`, `mkdir`, `rmdir`,
`cp`, and `mv`. These commands are used to list files,
change directories, create directories, remove directories,
copy files, and move files, respectively[1].

2. **Text Editors** This section discusses various text


editors available in the Linux Shell, such as `vi` and
`vim`. These editors are used to create and modify text
files[1].

3. **Shell Programming (Automation)** This section covers


shell programming, which involves writing scripts to
automate tasks. It includes topics like interpreted vs.
programming languages, shell interpreter (`bash`),
writing a basic bash script using the `echo` command,
local variables, reading user input using the `read`
command, local and global variables, environment
variables (`HOME`, `PATH`, `SHELL`), and environment
variables for the editor and login[1].

4. **Advanced Features** This section covers advanced


commands and features in the Linux Shell, such as `sed`
for pattern searching and replacement, `awk` for pretty
printing, `make utility` for Makefile writing, `signals and
traps`, useful websites, and a cheat sheet[1].

5. **Securing Files in Linux** This section discusses file


access permissions (FAPs) associated with the type of
users. It includes three types of permissions Read (`r`),
Write (`w`), and Execute (`x`)[1].

6. **Managing Documents** This section covers commands


and tools for managing documents, such as `find` for
locating files, redirections (`>`, `>>`), filters (`grep`, `wc`,
`cut`, `tr`), and pipes (`|`)[1].

7. **Redirection** This section discusses input redirection


(`cat < test <Enter>`), output redirection (`cat test1 >
test2`), and error output redirection (`cat dog 2> test2`)
[1].

8. **Filters** This section covers filters like `grep` for


searching a file for a specified pattern of characters and
displaying all the lines that contain the pattern[1].

9. **Pipes** This section discusses using the `tee`


command to save the output of a command on a hard
disk for later use[1].

10. **Creating Files Using ‘vi’ Editor** This section covers


creating files using the `vi` editor, which is a text editor
used in the Linux Shell[1].

11. **Automating Tasks – Shell Scripting** This section


covers command interpretation, the `echo` command for
displaying messages, creating and executing a shell
script, inserting comments in shell scripts, creating and
referencing variables, and executing shell commands[1].

These notes provide an overview of the commands and


topics covered in the Linux Shell file, along with their
descriptions and functions.

In more Description-

1. OS Intro
a. What is an OS An OS, or Operating System, is a
software program that manages computer
hardware and provides common services for
computer programs. It serves as an
intermediary between computer hardware and
user applications.
b. How does It work It starts with the boot process,
loads the kernel, and then manages processes,
memory, files, devices, and user interfaces. It
coordinates tasks like allocating resources,
scheduling processes, managing memory and
storage, handling input/output, and providing a
way for users to interact with the system.
Essentially, the OS serves as a bridge between
users, applications, and hardware, ensuring the
smooth and efficient operation of the computer.
c. Functions or jobs of OS The operating system
(OS) serves as the central software component
that oversees and coordinates various critical
functions within a computer system. These
functions include managing processes, memory,
files, devices, user interfaces, security measures,
networking capabilities, and error-handling
mechanisms. By orchestrating these tasks, the
OS acts as an intermediary between the
computer hardware and software applications,
ensuring smooth and efficient operation while
safeguarding the system against potential
threats and errors. In essence, the OS plays a
fundamental role in enabling users to interact
with the computer system effectively and
ensuring the optimal utilization of resources for
diverse computing tasks.
d. Types of OS
i. Single-user, Single-tasking Supports one
user and one program at a time.
ii. Single-user, Multi-tasking Allows a single
user to run multiple programs concurrently.
iii. Multi-user Enables multiple users to access
the system simultaneously.
iv. Real-time Handles tasks with strict timing
requirements.
v. Distributed Manages a group of
independent computers as a single system.
vi. Embedded Tailored for specific devices with
limited resources.
vii. Network Manages network resources and
facilitates communication between
computers.
viii. Mobile Designed for smartphones and
tablets, optimized for touchscreens and
mobility.

All about Linux OS


1. Introduction-
a. Managing Disk Files and Directories
b. Managing Documents
c. Text Editors
d. Shell Programming (automation)
e. Advance features
Managing Files and Directories-
1. ls(list) This command can list all the Directories and
Files in the Present Working Directory.
2. PWD(Present Working Directory) It is the command
that when executed shows the Directory in which the
terminal is working.
3. mkdir(Making Directory) The command present
mkdir helps in Making any directory of your desired
name the syntax goes here mkdir <desiredfilename>
4. rmdir(Remove Directory) rmdir command is used to
Remove any existing desired Directory in the Present
Working Directory and the syntax is rmdir
<desiredfilename>
5. cp(Copy) also known as copy is used to copy Files
and Directories present in the Present Working
Directory and the syntax goes like cp
<desiredfilename> <targetdirectory> or if want to
copy any Directory
6. mv(Move) The mv command in Linux has two distinct
functions, renaming files or directories and moving
them from one location to another within the file
system and the syntax is 5 mv <sourcefilename>
<newfilename> and for moving it is mv
<sourcefilename> <destinationdirectory>
● File System: It’s the overall structure that a Unix-like
operating system uses to organize and store files and
directories hierarchically. This makes data
management efficient and systematic.
● The root directory ‘/’: This is the base directory of the
file system. All other directories, files, and
subdirectories start from here. It’s like the trunk of a
tree from which all branches (directories) extend.
● Special Directories:

○ bin: This directory contains essential binary


executables and commands that are needed for
the operating system’s operations and for users
to execute commands.
○ dev: Short for ‘devices’, this directory holds
special files that represent hardware devices. It
allows the operating system to interface with
and manage hardware.
○ etc: This directory stores configuration files and
scripts that are used by the operating system.
It’s a crucial directory for system
administration.
○ lib: Contains libraries for system software and
language compilers. These libraries support the
creation of executable programs from source
code.
○ home: It includes the personal directories of all
the users on the system. Each user’s files,
settings, and more are stored here.
○ usr: Stands for ‘Unix System Resources’. It
contains additional user applications and files
that are not necessary for system booting, along
with their documentation.
○ var: Short for ‘variable’, this directory contains
files expected to grow in size, such as logs, spool
files, and cached data.
● File Naming
○ Up to 256 characters
○ Special characters except ‘/’
○ Can contain uppercase and lowercase letters
○ Case-sensitive
○ No blank or a tab
● Types of Files in Linux
○ Ordinary – created by the user. Includes data,
program,
○ object and executable files
○ Directory – contains information about the files
within
○ Special – system files like device information
files.
○ User cannot modify these files

● Main Commands for Linux Terminals:


○ touch: The primary purpose of touch is to create
empty files. If a file doesn’t exist, touch creates
it. If the file already exists, touch updates its
timestamps without altering the file’s contents.
When you type: touch the filename and press ⤶
Enter
○ cat:
■ Displays file contents.
■ Creates new files interactively.
■ Redirects content to other files.
■ Use tac for reverse order.
■ Handy for viewing and combining file
content.
○ head: Displaying File Contents:
● The head command reads the first few lines
of any text given to it as input and writes
them to standard output (which, by default,
is the display screen).
● By default, it prints the first 10 lines of the
specified files.
○ The tail command outputs the last part of the
files.
■ It’s often used to read the end of a file
where new lines are appended, such as log
files.
■ By default, it displays the last 10 lines of the
specified files.
■ The command can also monitor changes to
the file in real time.
■ It has several options:
● -n: Allows you to specify the number of
lines to display.
● -c: Let you display a certain number of
bytes.
● -q: Used when more than one file is
given, and it prevents the data from
each file from being preceded by its
filename.
■ The tail command is a powerful tool for
managing and monitoring files in a Linux
environment.
○ rm: The `rm` command in Linux is used for
removing objects such as files, directories,
symbolic links, and so on from the file system.
Here are some key points about the `rm`
command:
■ 1. **Basic Usage**: The basic syntax is `rm
[OPTION]... FILE...`. It works silently and
doesn't remove directories by default.
■ 2. **Removing Single File**: To remove a
single file, use `rm filename`.
■ 3. **Removing Multiple Files**: To remove
multiple files at once, use `rm filename1
filename2`.
■ 4. **Interactive Deletion**: The `-i` option
prompts the user for confirmation before
removing each file.
■ 5. **Force Deletion**: The `-f` option forces
the removal of a file, even if it's write-
protected.
■ 6. **Recursive Deletion**: The `-r` or `-R`
option allows `rm` to delete all files and
sub-directories recursively of the parent
directory.
■ 7. **Version Information**: The `--version`
option displays the version of `rm` currently
running on your system.
○ more: The `more` command in Linux is used to
view the contents of a file in a page-by-page
manner. Here are some key points about the
`more` command:
■ 1. **Basic Usage**: The basic syntax is
`more [OPTION]... FILE...`. It displays one
screen at a time and allows the user to
scroll up and down through the page.
■ 2. **Navigation**: While viewing the text file,
use these controls:
■ `Enter key`: Scroll down line by line.
■ `Space bar`: Go to the next page.
■ `b key`: Go back one page.
■ 3. **Options**:
■ `-d` Displays help for navigation.
■ `-f`: Does not wrap long lines.
■ `-p`: Clears the screen before displaying the
text.
■ `-c`: Displays the pages in the same area by
overlapping the previously displayed text.
■ `-s`: Squeezes multiple blank lines into one
single blank line.
■ `-u`: Omit the underlines.
■ 4. **Searching**: The `+/pattern` option is
used to search the string inside your text
document.
■ 5. **Line Number**: The `+num` option
displays the text after the specified number
of lines of the document.
■ 6. **Pipe Usage**: The `more` command can
be used after a pipe to see long outputs.
■ Please note that unlike `less`, the `more`
command does not support backward
scrolling (except for going back one page).
○ Linux commands related to Users and Groups:
■ 1. **whoami**: Displays the username of the
current user when this command is invoked.
■ 2. **which**: Shows the full path of (shell)
commands.
■ 3. **history**: Used to view the previously
executed command.
■ 4. **alias/unalias**: `alias` is used to create
shortcuts for commands and `unalias` is
used to remove aliases.
■ 5. **Arrow keys**: In the terminal, arrow
keys can be used to navigate through
previously typed commands.
■ 6. **!!**: Executes the last entered command.
■ 7. **!<id>**: Executes a specific command
from history identified by id.
■ 8. **!<cmd>**: Executes the last command
starting with ‘cmd’.
■ These commands are very useful for
navigating and executing commands in the
Linux terminal. Let me know if you need
more information about any of these
commands.
● Additional Commands
○ **rm ***: This command removes all files in the
current directory.
○ *ls –l .txt: This command lists all .txt files in long
format.
○ **ls –al ***: This command lists all files, including
hidden ones, in long format.
○ ls –al .: This command lists all files with an
extension, including hidden ones, in long format.
○ ls –al; touch abc; ls –al: This command lists all
files in long format, creates a new file named
abc, and then lists all files again to show the
newly created file.
● More Exercise:-
○ 1. **Create the Tree Structure:**
■ - Create a directory named `f3`.
■ - Inside `f3`, create directories named `g31`
and `g32`, and a file named `g33`.
○ - Inside `g31`, create directories named `h31`
and `h32`.
■ - In the directory `h31`, create a file named
'i311'.
■ - In the directory ‘h32’, create a file named
'i321'.
■ - Create another directory at the same level
as ‘f3’ and name it ‘f4’.
■ - Inside ‘f4’, create directories named ‘g41’
and ‘g42’.
■ - In the directory ‘g41’, create files named
'h411' and 'h412'.
○ 2. **Swap Files:**
■ - Swap files i311 with i321, meaning rename
i311 to i321, and i321 to i311.
○ 3. **Move File:**
■ - Move file h411 to g32 while being in the f3
directory.
○ 4. **Copy File:**
■ - Copy file h412 to h32 while being in the
g41 directory.
○ These steps will help you complete the exercise
per the instructions in the image. Remember to
navigate to the correct directories before
performing operations like moving or copying
files. This exercise helps you understand file and
directory management in a Unix-like operating
system. It covers creating directories and files,
renaming files, and moving and copying files
between directories. It also demonstrates the
importance of the current working directory
when performing file operations.
More Commands on Securing Files

● chmod: This command is used to change file


access permissions in Linux.

● Symbolic Mode: In symbolic mode, you can


modify the permissions of a file or directory by
specifying letters instead of numbers. The letters
used in symbolic mode are:

○ u: User
○ g: Group
○ o: Others
○ a: All (User, Group, and Others)
● Grant Permission (+): The + symbol is used to
grant permissions. For example:

○ chmod u+x <filename>: This command


grants execute permission to the user for
the specified file.
○ chmod u+x,g-w,o-r,o-w <filename>: This
command grants execute permission to the
user, removes write permission for the
group, and removes read and write
permissions for others for the specified file.
● Remove Permission (-): The - symbol is used to
remove permissions. For example:

○ chmod g-w <filename>: This command


removes write permission from the group
for the specified file.
● cut:
○ Basic Syntax: The basic syntax of the cut
command is cut OPTION... [FILE]... If a file
is not specified, cut reads from standard input.
○ Byte Position: The -b option allows you to
extract specific bytes from each line. For
example, cut -b 1,2,3 file.txt extracts the
first three bytes from each line of file.txt.
○ Character: The -c option allows you to extract
specific characters from each line. For example,
cut -c 1,2,3 file.txt extracts the first three
characters from each line of file.txt.
○ Field: The -f option allows you to extract fields
from each line, separated by a delimiter. For
example, cut -f 1,2 -d ',' file.txt extracts
the first two fields from each line of file.txt,
where fields are separated by commas.
○ Delimiter: The -d option allows you to specify a
delimiter. By default, the delimiter is a tab
character.

● pipes:
○ Join Commands: Pipes let you join commands.
The output of one command becomes the input
of the next.
○ Data Flow: They allow data to flow from one
command to another.
○ Avoid Extra Files: They help avoid creating extra
files for storing output.
○ One-Way Flow: Data flows in one direction, from
left to right.

Here’s how you can use pipes:

● Example 1: ls | grep file.txt. This command


finds the file named file.txt in the list of all
files and directories.
● Example 2: ls -l | more. This command shows
the list of all files and directories one screen at a
time.
tee: Sure, here’s a simple explanation of the use of tee in
a Linux terminal:

1. Duplicate Output: tee is used to duplicate the output


of a command. It can send output to the terminal and
a file at the same time.
2. Pipe and Save: It allows you to save the output of a
command to a file and also continue the data down
the pipeline for further processing.

Here’s how you can use tee:

● Example 1: ls | tee file.txt. This command lists


all files and directories, displays the output on the
terminal, and also saves it to file.txt.
● Example 2: ls | tee file.txt | more. This
command lists all files and directories, saves the
output to file.txt, and also displays the output one
screen at a time using more.
● vi editor:
○ Text Editing: vi is a text editor that allows you to
create and edit files directly in the terminal.
○ Programming: It’s often used for writing and
editing code because it has features like syntax
highlighting.
○ Server Administration: Since vi is pre-installed
on almost every Unix-like system, it’s commonly
used for editing configuration files on servers.
Here’s how you can use vi:
● Open a File: Type vi filename in the terminal.
Replace the filename with the name of the file
you want to open or create.
● Insert Mode: Press i to switch to insert mode.
This allows you to insert text into your file.
● Command Mode: Press Esc to switch to command
mode. This allows you to save changes, search
text, and perform other commands.
● Save and Quit: In command mode, type: wq and
press Enter to save your changes and quit vi.
● Quit Without Saving: In command mode, type:q!
and press Enter to quit vi without saving your
changes.








● SHLVL EXERCISE:

Sure, I can help you with that. The exercise is about


creating a set of scripts that call each other and echo
the SHLVL value. Here’s how you can create these
scripts:

1. main.sh
○ #!/bin/bash
○ echo "SHLVL in main =
$SHLVL"
○ ./f1.sh
○ ./f2.sh
○ ./f3.sh

2. f1.sh
○ #!/bin/bash
○ echo "SHLVL in f1 = $SHLVL"
○ ./f4.sh

3. f2.sh
○ #!/bin/bash
○ echo "SHLVL in f2 = $SHLVL"
○ ./f5.sh

4. f3.sh
○ #!/bin/bash
○ echo "SHLVL in f3 = $SHLVL"
○ ./f6.sh

5. f4.sh, f5.sh, f6.sh


○ #!/bin/bash
○ echo "SHLVL in fx = $SHLVL"
Replace x with 4, 5, and 6 for the respective scripts.

Remember to make all these scripts executable by


running chmod +x script_name.sh for each script. Then,
you can run the main script using ./main.sh in your
terminal. This will execute the scripts in the specified
order and print the SHLVL value for each script. The SHLVL
variable in bash indicates the depth of the shell.



● Expr:
○ Command Type: The command is an ‘expr’
command used in shell scripting.
○ Variable Storage: In shell scripting, variables
are stored as strings, even if they are integers.
○ Arithmetic Operations: The ‘expr’ command
allows arithmetic operations on these string-type
variables.
○ Example Given: Variables ‘a’ and ‘b’ are assigned
values 4 and 5 respectively. The ‘expr’ command
is used to add these variables: expr $a + $b.
○ Operator Spacing: There should be a space on
either side of the arithmetic operator (+).
○ Special Characters Handling: For operators like
‘*’, a backslash (\) must precede them, or else
they will be considered wildcard characters.
● Remember, the ‘expr’ command is a powerful tool in
shell scripting for performing arithmetic operations
and handling variables. It’s important to use it
correctly to avoid unexpected results. Always ensure
proper spacing around operators and handle special
characters with care.

● Practice Question on page 87:


○ The practice question you've
provided is asking for a shell
script that calculates the
number of unqualified
candidates in a screening
examination. The script
should take two inputs: the
total number of candidates
who appeared for the
examination and the number
of qualified candidates. To
calculate the number of
unqualified candidates, you
would subtract the number of
qualified candidates from the
total number of candidates.
○ Here is a simple shell script
that accomplishes this task:
○ ```bash
○ #!/bin/bash
○ # Prompt the user to enter the
total number of candidates
○ echo "Enter the total number
of candidates who appeared
for the examination:"
○ read total_candidates
○ # Prompt the user to enter the
number of qualified
candidates
○ echo "Enter the number of
qualified candidates:"
○ read qualified_candidates
○ # Calculate the number of
unqualified candidates
○ let
unqualified_candidates=$tota
l_candidates-
$qualified_candidates
○ # Output the result
○ echo "The number of
unqualified candidates is:
$unqualified_candidates"
○ To use this script:
○ 1. Save it to a file, for
example
`calculate_unqualified.sh`.
○ 2. Make the script executable
with the command `chmod +x
calculate_unqualified.sh`.
○ 3. Run the script using
`./calculate_unqualified.sh`.
○ 4. Enter the required numbers
when prompted.
● The script will then display the
number of unqualified candidates.



● Practice Question:
○ The task described in the image is
to write a shell script that asks the
user to enter their age and then
prints a message based on the age
range the user falls into. Here's a
simple shell script to accomplish
this:
○ ```bash
○ #!/bin/bash
○ # Ask the user to enter their age
○ echo "Please enter your age:"
○ read age
○ # Check the age range and print
the appropriate message
○ if [ "$age" -lt 13 ]; then
■ echo "You are a kid."
○ elif [ "$age" -ge 13 ] && [ "$age" -le
19 ]; then
■ echo "You are a teenager."
○ elif [ "$age" -ge 20 ] && [ "$age" -le
42 ]; then
■ echo "You are growing old."
○ else
■ echo "Age range not covered
by the script."
○ Fi
○ ```
○ To use this script:
■ 1. Save it to a file, for
example `age_message.sh`.
■ 2. Make the script executable
with the command `chmod +x
age_message.sh`.
■ 3. Run the script using
`./age_message.sh`.
■ 4. Enter the age when
prompted.
■ The script will then display
the appropriate message
based on the age entered.

● Practice Questions:
○ 1. Take two numbers from the
user and display the greater
number.
○ 2. Take three numbers from the
user and display them in
decreasing order.
○ 3. Take four numbers from the
user and display them in
increasing order.
○ Here are simple shell scripts for
each task:
○ **Task 1: Display the greater of
two numbers**
■ ```bash
■ #!/bin/bash
■ echo "Enter the first number:"
■ read num1
■ echo "Enter the second
number:"
■ read num2
■ if [ "$num1" -gt "$num2" ];
then
● echo "The greater
number is: $num1"
○ else
■ echo "The greater number is:
$num2"
○ fi
○ ```
○ **Task 2: Display three numbers in
decreasing order**
○ ```bash
■ #!/bin/bash
■ echo "Enter the first number:"
■ read num1
■ echo "Enter the second
number:"
■ read num2
■ echo "Enter the third
number:"
■ read num3
■ # Using sort command to
sort the numbers in
decreasing order
■ echo -e "$num1\n$num2\
n$num3" | sort -nr
○ ```
○ **Task 3: Display four numbers in
increasing order**
○ ```bash
■ #!/bin/bash
■ echo "Enter the first number:"
■ read num1
■ echo "Enter the second
number:"
■ read num2
■ echo "Enter the third
number:"
■ read num3
■ echo "Enter the fourth
number:"
■ read num4
■ # Using the sort command to
sort the numbers in
increasing order
■ echo -e "$num1\n$num2\
n$num3\n$num4" | sort -n
○ ```
● To use these scripts:
○ 1. Save each script to a separate
file, for example
`greater_number.sh`,
`sort_decreasing.sh`, and
`sort_increasing.sh`.
○ 2. Make each script executable
with the command `chmod +x
<script_name>`.
○ 3. Run the scripts using
`./<script_name>`.
○ 4. Enter the numbers when
prompted.
○ Each script will then display the
output as per the task
requirements.

● Practice Questions:
○ #!/bin/bash
○ # Prompt the user for a file
name
○ echo "Please enter a
filename:"
○ read filename
○ # Check if the file/directory
exists
○ if [ -e "$filename" ]; then
○ echo "The file/directory
'$filename' exists."
○ # Check if the file is
readable
○ if [ -r "$filename" ]; then
○ echo "The file is
readable."
○ else
○ echo "The file is not
readable."
○ fi
○ # Check if the file is
writable
○ if [ -w "$filename" ]; then
○ echo "The file is
writable."
○ else
○ echo "The file is not
writable."
○ fi
○ # Check if the file is
executable
○ if [ -x "$filename" ]; then
○ echo "The file is
executable."
○ else
○ echo "The file is not
executable."
○ fi
○ else
○ echo "The file/directory
'$filename' does not exist."
○ fi
● “ 2:
○ #!/bin/bash
○ # Prompt the user for a file
name
○ echo "Please enter a
filename:"
○ read name
○ # Check if the file/directory
exists using the variable
'name'
○ if [ -e "$name" ]; then
○ echo "The file/directory
'$name' exists."
○ # Check if the file is
readable
○ if [ -r "$name" ]; then
○ echo "The file is
readable."
○ else
○ echo "The file is not
readable."
○ fi
○ # Check if the file is
writable
○ if [ -w "$name" ]; then
○ echo "The file is
writable."
○ else
○ echo "The file is not
writable."
○ fi
○ # Check if the file is
executable
○ if [ -x "$name" ]; then
○ echo "The file is
executable."
○ else
○ echo "The file is not
executable."
○ fi
○ else
○ echo "The file/directory
'$name' does not exist."
○ fi
● Case code:
○ echo -n "Enter a month
number (0 for Jan, 1 for Feb,
so on): ": This line prints a
message asking the user to
enter a month number, where
0 represents January, 1
represents February, and so
on. The -n option prevents a
newline character from being
added at the end, so the
cursor stays on the same line
after the message.
○ read str: This line reads the
user’s input from the
keyboard and stores it in a
variable called str.
○ case ${str} in: This line starts
a case statement, which will
compare the value of str to
the patterns specified in the
following lines.
○ 0) echo "January" ;;: If the
value of str is 0, it prints
“January” and then exits the
case statement.
○ 1) echo "February" ;;: If the
value of str is 1, it prints
“February” and then exits the
case statement.
○ *) echo "After February" ;;:
The * character is a wildcard
that matches any value. So if
str is neither 0 nor 1, it prints
“After February”.
○ esac: This line marks the end
of the case statement.
● While loop in bash:
○ a=1: This line initializes the
variable a with the value 1.
This is the starting point of
our loop.
○ while [ $a –le 10 ]: This line
starts a while loop. The
condition for the loop to
continue is $a –le 10, which
means “while the value of a is
less than or equal to 10”.
○ do: This keyword signifies the
start of the code block that
will be executed in each
iteration of the loop.
○ echo $a: This line prints the
current value of a to the
console.
○ ((a=a+1)): This line increments
the value of a by 1.
○ done: This keyword signifies
the end of the while loop.
After the keyword, the script
goes back to the while
condition and checks it again.
If the condition is still true,
the loop executes again. If the
condition is false, the script
ends.
● Until loop in bash:
○ a=1: This line initializes the
variable a with the value 1.
This is the starting point of
our loop.
○ until [ $a –ge 10 ]: This line
starts an until loop. The loop
will continue to execute as
long as the value of a is less
than 10. As soon as the value
of a becomes 10 or greater,
the loop stops.
○ do: This keyword signifies the
start of the code block that
will be executed in each
iteration of the loop.
○ echo $a: This line prints the
current value of a to the
console.
○ ((a=a+1)): This line increments
the value of a by 1.
○ done: This keyword signifies
the end of the until loop. After
the done keyword, the script
goes back to the until
condition and checks it again.
If the condition is still false,
the loop executes again. If the
condition is true, the script
ends.
● For loop in bash:
○ for the name in Deven Neeraj
Shilpi: This line starts a for a
loop. The variable name will
take on each of the values
listed (Deven, Neeraj,
individually by one.
○ do: This keyword signifies the
start of the code block that
will be executed in each
iteration of the loop.
○ echo “${name}”: This line
prints the current name value
to the console. The ${name}
syntax is used to reference
the value of the variable
name.
○ done: This keyword signifies
the end of the for loop.
● Another example of for loop in
bash:
○ list=“Deven Neeraj Shilpi”:
This line initializes the
variable list with a string
containing three names:
“Deven”, “Neeraj”, and
“Shilpi”.
○ for the name in the $list: This
line starts a for loop. The
variable name will take on
each of the words in the list
one by one. In shell scripting,
a string variable is split into
words when it is used without
quotes, and each word is
considered a separate item.
○ do: This keyword signifies the
start of the code block that
will be executed in each
iteration of the loop.
○ echo “${name}”: This line
prints the current value of the
name to the console. The $
{name} syntax is used to
reference the value of the
variable name.
○ done: This keyword signifies
the end of the for loop.
● Practice Question on page 125:
○ #!/bin/bash
○ # Initialize counters
○ file_count=0
○ dir_count=0

○ # Loop through all items in
the current directory
○ for item in $(ls -A)
○ do
○ # If the item is a directory,
increment the directory
counter
○ if [ -d "$item" ]
○ then
○ ((dir_count++))
○ # If the item is a file,
increment the file counter
○ elif [ -f "$item" ]
○ then
○ ((file_count++))
○ fi
○ done
○ # Display the counts
○ echo "Number of directories:
$dir_count"
○ echo "Number of files:
$file_count"
● Another for loop example:
○ for ((a=1;a<=10;a=a+1))
○ Do
■ echo “$a”
○ done
● Addon into for loop:
○ #!/bin/bash
○ MAX=10000
○ for ((nr=1; nr<$MAX; nr++))
○ Do
■ let “t1 = nr % 5”
○ if [ “$t1” -ne 3 ]
○ Then
■ continue
○ fi
○ let “t2 = nr % 7”
○ if [ “$t2” -ne 4 ]
○ Then
○ continue
○ fi
○ let “t3 = nr % 9”
○ if [ “$t3” -ne 5 ]
○ Then
■ continue
○ Fi
■ break # What happens
when you comment out
this line? Why?
○ done
○ echo “Number = $nr”
○ exit
● Example of Parameter Handling:
○ cp –r dir1 dir2
○ $0 – “cp”
○ $1 – “-r”
○ $2 – “dir1”
○ $3 – “dir2”
○ echo $(($1+$2))
○ Answer:
■ echo cp -r dir1
● Another example of Parameter
Handling with arguments:
○ #!/bin/bash
○ echo “The name of the
program is $0”
○ echo “The first argument is
$1”
○ echo “The number of
arguments $#”
○ echo “And they are $*”
● Another one with shift command:
○ echo “The value of \$# = $#”
○ echo “The value of \$* = $*”
○ shift
○ echo “The modified number of
arguments $#”
○ echo “And they are modified
as $*”
● Practice Questions on pg 127:
○ Q1)
■ for i in {1..50}
■ do
■ if [ $((i%2)) -eq 0 ]
■ then
■ echo $i
■ fi
■ done
○ Q2)
■ count=0
■ for i in {1..50}
■ do
■ if [ $((i%2)) -eq 0 ]
■ then
■ echo -n "$i "
■ ((count++))
■ if [ $((count%5)) -eq
0]
■ then
■ echo
■ fi
■ fi
■ done
■ if [ $((count%5)) -ne 0 ]
■ then
■ echo
■ fi
○ Q3)
■ echo "Enter the minimum
range:"
■ read min
■ echo "Enter the
maximum range:"
■ read max
■ if [ $min -gt $max ]
■ then
■ echo "Error: Minimum
range is greater than
maximum range."
■ exit 1
■ fi
■ count=0
■ for i in $(seq $min $max)
■ do
■ if [ $((i%2)) -eq 0 ]
■ then
■ echo -n "$i "
■ ((count++))
■ if [ $((count%5)) -eq
0]
■ then
■ echo
■ fi
■ fi
■ done
■ if [ $((count%5)) -ne 0 ]
■ then
■ echo
■ fi
○ Q4)
■ #!/bin/bash
■ # Check if two arguments
are passed
■ if [ "$#" -ne 2 ]; then
■ echo "Please provide
two arguments: min and
max"
■ exit 1
■ fi
■ min=$1
■ max=$2
■ # Print even numbers in
the range
■ for (( i=min; i<=max; i+
+ ))
■ do
■ if [ $((i%2)) -eq 0 ];
then
■ echo $i
■ fi
■ done
○ Q5)
■ #!/bin/bash
■ # Check if two arguments
are passed
■ if [ "$#" -ne 2 ]; then
■ echo "Usage:
./printEven <min> <max>"
■ echo "Prints the even
numbers in the range
[min:max]."
■ echo "Both arguments
are mandatory."
■ exit 1
■ fi
■ min=$1
■ max=$2
■ # Print even numbers in
the range
■ for (( i=min; i<=max; i+
+ ))
■ do
■ if [ $((i%2)) -eq 0 ];
then
■ echo $i
■ fi
■ done
○ Q6)
■ #!/bin/bash
■ # Check if at least two
arguments are passed
■ if [ "$#" -lt 2 ]; then
■ echo "Usage:
./printEven <min> <max>
[printformat]"
■ echo "Prints the even
numbers in the range
[min:max]."
■ echo "Both min and
max arguments are
mandatory."
■ echo "printformat is
optional and can be 1 or
2. By default, 1 is used."
■ exit 1
■ fi
■ min=$1
■ max=$2
■ printformat=${3:-1}
■ # Print even numbers in
the range
■ for (( i=min; i<=max; i+
+ ))
■ do
■ if [ $((i%2)) -eq 0 ];
then
■ if [ "$printformat" -
eq 1 ]; then
■ echo $i
■ elif [ "$printformat"
-eq 2 ]; then
■ echo -n "$i "
■ fi
■ fi
■ done

■ # Print a newline if
printformat is 2
■ if [ "$printformat" -eq 2 ];
then
■ echo
■ fi

○ Q7)
○ Q8)

In shell scripting, the difference between a


variable that is exported and one that is not
exported lies in their scope, specifically
whether they are accessible to child
processes or not.

● Non-exported variables: These are also


known as local variables. They are only
available in the current shell where they are
defined. Child processes (i.e., processes
started by the current shell) do not have
access to these variables.
● Exported variables: These are also known as
environment variables. When a variable is
exported, it is available not only in the
current shell but also to any child processes
started by the current shell. This is useful
when you want to share information
between different shell scripts or processes.

Here’s an example to illustrate this:

■ # Define a local variable


■ localvar="I am local"
■ # Define an environment
variable
■ export envvar="I am
global"
■ # Start a new shell
■ bash
■ # Try to print the
variables
■ echo $localvar # This
will not print anything
because localvar is not
available in the child
shell
■ echo $envvar # This
will print "I am global"
because envvar is an
environment variable
○ Q9)

In a shell script, you can read arguments that are passed


to it using special variables. Here’s how it works:

● $0: This variable contains the name of the script


itself.
● $1, $2, $3, …, $9: These variables contain the first,
second, third, …, ninth arguments passed to the script.
● ${10}, ${11}, ${12}, …: For arguments beyond 9, you
need to use curly braces.
● $* or $@: These variables contain all arguments
passed to the script.
● $#: This variable contains the number of arguments
passed to the script.

Here’s an example of a script that prints its


arguments:

■ #!/bin/bash
■ echo "The script name:
$0"
■ echo "The first argument:
$1"
■ echo "The second
argument: $2"
■ echo "All arguments: $@"
■ echo "The number of
arguments: $#"

If you run this script with ./myscript arg1


arg2 arg3, it will print:

■ The script name:


./myscript
■ The first argument: arg1
■ The second argument:
arg2
■ All arguments: arg1 arg2
arg3
■ The number of
arguments: 3
This way, you can read and use the arguments
passed to your shell script. Remember that these
are positional parameters, so the order in which
arguments are passed matters. Also, if an
argument contains spaces, you should quote it
when passing it to the script to ensure it’s
treated as a single argument. For example,
./myscript "arg1 with spaces" arg2.

○ Q10)
■ You can use the find
command in Unix/Linux
to find files based on
various criteria, including
the modification time.
However, finding files
created within a specific
time range like between
10 a.m. to 5 p.m. is a bit
tricky because
Unix/Linux filesystems
typically do not keep
track of the creation time
of files.
■ But if you’re interested in
files that were modified
within a certain time
range, you can use the -
newermt option of the
find command, which
finds files that are
modified between two
timestamps.
■ Here’s an example of how
you can find files
modified between 10 a.m.
and 5 p.m. today:
■ # Get today's date in
YYYY-MM-DD format
■ today=$(date +%Y-%m-
%d)

■ # Find files in the current
directory that were
modified between 10 a.m.
and 5 p.m.
■ find . -type f -newermt
"$today 10:00" ! -
newermt "$today 17:00"

■ This command will print
the paths of files in the
current directory (and its
subdirectories) that were
modified between 10 a.m.
and 5 p.m. today.
■ Please note that this
command might not work
as expected if files were
modified during the
specified time range on a
previous day. Also, this
command relies on the
system clock and
timezone being set
correctly.
■ If you specifically need
to track the creation time
of files, you might need
to use a different
filesystem or operating
system that supports this
feature, or manually log
file creation times in an
application. Please
consult the
documentation of your
operating system or
filesystem for more
information.
■ Also, please note that the
above command is for
bash shell and similar
shells. If you’re using a
different shell or
operating system, you
might need to use a
different command. If
you’re not sure, please
check the man pages or
documentation for your
shell or operating system.
○ Q11)
■ #!/bin/bash

■ # Check if three
arguments are supplied
■ if [ $# -ne 3 ]
■ then
■ echo "Error: Three
arguments are required."
■ exit 1
■ fi
■ # Read the arguments
■ num1=$1
■ num2=$2
■ num3=$3
■ # Find the biggest
number
■ if [ $num1 -gt $num2 ]
&& [ $num1 -gt $num3 ]
■ then
■ echo "The biggest
number is $num1"
■ elif [ $num2 -gt $num1 ]
&& [ $num2 -gt $num3 ]
■ then
■ echo "The biggest
number is $num2"
■ else
■ echo "The biggest
number is $num3"
■ fi
○ Q12)
■ #!/bin/bash
■ # Print the current date
and time
■ echo "Current date and
time: $(date)"
■ # Print the username
■ echo "Username: $USER"
■ # Print the current
directory
■ echo "Current directory: $
(pwd)"
○ Q13)

Sure, here are the bash scripts for each of


your requests:
1. Copy /etc/passwd file into your present
working directory and change the delimiter
from : to ;:
● cp /etc/passwd
./passwd_copy &&
sed 's/:/;/g'
passwd_copy >
passwd_semicolon

2. Display the fourth field till the last field of


each row of the new file:
● awk -F';'
'{for(i=4;i<=NF;i++)
printf $i (i==NF?
RS:FS)}'
passwd_semicolon

3. Do the above two questions on one single


command line:
● cp /etc/passwd
./passwd_copy &&
sed 's/:/;/g'
passwd_copy >
passwd_semicolon
&& awk -F';'
'{for(i=4;i<=NF;i++)
printf $i (i==NF?
RS:FS)}'
passwd_semicolon
4. Change the default working directory to
~/work for all opened terminals. Add this
line to your ~/.bashrc or ~/.bash_profile
file:
● cd ~/work

5. Display a welcome message whenever you


open a terminal. Add this line to your
~/.bashrc or ~/.bash_profile file:
● echo "Welcome
<your-name> to the
world of Linux
Scripting!"

Replace <your-name> with your actual


name.

6. Write a script to ask the user how many


prime numbers they want and then display
that many prime numbers starting from 1:
● #!/bin/bash
● echo "How many
prime numbers do
you want?"
● read n
● count=0
● num=2
● while [ $count -lt
$n ]
● Do
● div_count=0
○ for i in `seq 1
$num`
■ Do
○ if [ `expr $num
% $i` -eq 0 ]
○ Then
● div_count=`expr
$div_count + 1`
● fi
● Done
● if [ $div_count -eq
2]
■ then
■ echo $num
■ count=`expr
$count + 1`
■ fi
■ num=`expr $num + 1`
■ done

7. Do the above question with the use of parameter


instead of asking the user:
■ #!/bin/bash
■ n=$1
■ count=0
■ num=2

■ while [ $count -lt $n ]
■ do
■ div_count=0
■ for i in `seq 1 $num`
■ do
■ if [ `expr $num %
$i` -eq 0 ]
■ then
■ div_count=`expr
$div_count + 1`
■ fi
■ done
■ if [ $div_count -eq 2 ]
■ then
■ echo $num
■ count=`expr $count
+ 1`
■ fi
■ num=`expr $num + 1`
■ done

You can run this script with one


argument like so: ./primeNumbers.sh
<n>. This will print the first <n> prime
numbers. Please replace <n> with your
desired number. For example,
./primeNumbers.sh 10 will print the
first 10 prime numbers.

● Function practice:
■ #!/bin/bash
■ # Recursive function to
calculate factorial
■ factorial() {
■ if [ $1 -le 1 ]; then
■ echo 1
■ Else
■ last_factorial=$
(factorial $(($1-1)))
■ echo $(($1 *
$last_factorial))
■ fi
■ }
■ # Call the function with
the number you want to
calculate the factorial of
■ factorial $1
○ Practice:
■ #!/bin/bash
■ # Print the table header
■ printf "%-8s %-8s %-8s
%-8s\n" "Char" "Hex"
"Dec" "Oct"
■ # Loop over the ASCII
values
■ for ((i=32; i<=126; i++)); do
■ # Convert the ASCII
value to a character,
hexadecimal, and octal
■ char=$(awk -v dec=$i
'BEGIN{printf "%c", dec}')
■ hex=$(awk -v dec=$i
'BEGIN{printf "%x",
dec}')
■ oct=$(awk -v dec=$i
'BEGIN{printf "%o",
dec}')
■ # Print the character
and its values
■ printf "%-8s %-8s %-8s
%-8s\n" "$char" "$hex"
"$i" "$oct"
■ done
A
L
L
D
O
N
E!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!

You might also like