Notes
Notes
Here are the notes for each command and topic in the
provided Linux Shell file
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.
○ u: User
○ g: Group
○ o: Others
○ a: All (User, Group, and Others)
● Grant Permission (+): The + symbol is used to
grant permissions. For example:
● 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.
●
●
●
●
●
●
●
●
●
●
●
●
●
● SHLVL EXERCISE:
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
●
●
●
●
● 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:
○ 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)
■ #!/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: $#"
○ 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)
● 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!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!