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

7th Chapter Unix

A shell script is a file containing a set of commands executed by a command line interpreter (CLI) in a Linux system. Common uses include task automation, customization of the command line environment, and file management. The document also provides examples of shell scripts, explaining concepts such as the shebang, variable assignment, loops, and conditional statements.

Uploaded by

arindamghorui03
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)
3 views

7th Chapter Unix

A shell script is a file containing a set of commands executed by a command line interpreter (CLI) in a Linux system. Common uses include task automation, customization of the command line environment, and file management. The document also provides examples of shell scripts, explaining concepts such as the shebang, variable assignment, loops, and conditional statements.

Uploaded by

arindamghorui03
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/ 24

What is Shell Script?

Well, the shell is a CLI (command line interpreter), which runs in a text window where users can
manage and execute shell commands. On the other hand, the process of writing a set of
commands to be executed on a Linux system A file that includes such instructions is called a
bash script.

Uses of Shell Scripts

Below are some common uses of Shell Script:

• Task Automation - It can be used to automate repetitive tasks like regular backups and
software installation tasks.

• Customization - One can use shell scripts to design its command line environment and
easily perform its task as per needs.

• File Management - The shell scripts can also be used to manage and manipulate files
and directories, such as moving, copying, renaming, or deleting files.

Shell Script Examples in Linux

1) What does the shebang (#!) at the beginning of a shell script indicate?

The shebang (#!) at the beginning of a script indicates the interpreter that should be used to
execute the script. It tells the system which shell or interpreter should interpret the script's
commands.

For example: Suppose we have a script named myscript.sh written in the Bash shell:

shebang

In this example:

• The #!/bin/bash at the beginning of the script indicates that the script should be
interpreted using the Bash shell.

• The echo commands are used to print messages to the terminal.

2) How do you run a shell script from the command line?


To run a shell script from the command line, we need to follow these steps:

• Make sure the script file has executable permissions using the chmod command:

chmod +x myscript.sh

• Execute the script using its filename:

./myscript.sh

Here you have to replace "myscrtipt.sh" with yors script name.

3) Write a shell script that prints "GeeksforGeeks" to the terminal.

Create a script name `myscript.sh` (we are using `vim` editor, you can choose any editor)

vim myscript.sh

#!/bin/bash
# This script prints "GeeksforGeeks" to the terminal
echo "GeeksforGeeks"

print
name

We make our script executable by using `chmod +x` then execute with `./myscipt.sh` and get our
desired output "GeeksforGeeks".

4) Explain the purpose of the echo command in shell scripting.

The echo command is used to display text or variables on the terminal. It's commonly used for
printing messages, variable values, and generating program output.

echo command

In this example we have execute `echo` on terminal directely , as it works same inside shell
script.
5) How can you assign a value to a variable in a shell script?

Variables are assigned values using the assignment operator =.

For example:

#!/bin/bash
# Assigning a value to a variable
name="Jayesh"
age=21
echo $name $age

Explanation:

• The name variable is assigned the value "Jayesh".

• The age variable is assigned the value 21.

• echo is used to print and `$name` `$age` is used to call the value stored in the variables.

6) Write a shell script that takes a user's name as input and greets them.

Create a script name `example.sh`.

#!/bin/bash
# Ask the user for their name
echo "What's your name?"
read name
# Greet the user
echo "Hello, $name! Nice to meet you."

Explanation:

• #!/bin/bash: This is the shebang line. It tells the system to use the Bash interpreter to
execute the script.

• # Ask the user for their name: This is a comment. It provides context about the
upcoming code. Comments are ignored by the interpreter.
• echo "What's your name?": The echo command is used to display the text in double
quotes on the terminal.

• read name: The read command waits for the user to input text and stores it in the
variable name.

• echo "Hello, $name! Nice to meet you.": This line uses the echo command to print a
greeting message that includes the value of the name variable, which was collected from
the user's input.

7) How do you add comments to a shell script?

Comments in shell scripting are used to provide explanations or context to the code. They are
ignored by the interpreter and are only meant for humans reading the script. You can add
comments using the # symbol.

#!/bin/bash
# This is a comment explaining the purpose of the script
echo "gfg"

8) Create a shell script that checks if a file exists in the current directory.

Here's a script that checks if a file named "example.txt" exists in the current directory:

#!/bin/bash
file="example.txt"
# Check if the file exists
if [ -e "$file" ]; then
echo "File exists: $file"
else
echo "File not found: $file"
fi

Explanation:
1. #!/bin/bash: This is the shebang line that specifies the interpreter (/bin/bash) to be used
for running the script.

2. file="example.txt": This line defines the variable file and assigns the value "example.txt"
to it. You can replace this with the name of the file you want to check for.

3. if [ -e "$file" ]; then: This line starts an if statement. The condition [ -e "$file" ] checks if
the file specified by the value of the file variable exists. The -e flag is used to check for
file existence.

4. echo "File exists: $file": If the condition is true (i.e., the file exists), this line prints a
message indicating that the file exists, along with the file's name.

5. else: If the condition is false (i.e., the file doesn't exist), the script executes the code
under the else branch.

6. echo "File not found: $file": This line prints an error message indicating that the
specified file was not found, along with the file's name.

7. fi: This line marks the end of the if statement.

Finding file

9) What is the difference between single quotes (') and double quotes (") in shell scripting?

Single quotes (') and double quotes (") are used to enclose strings in shell scripting, but they
have different behaviors:

• Single quotes: Everything between single quotes is treated as a literal string. Variable
names and most special characters are not expanded.

• Double quotes: Variables and certain special characters within double quotes are
expanded. The contents are subject to variable substitution and command substitution.

#!/bin/bash

abcd="Hello"
echo '$abcd' # Output: $abcd
echo "$abcd" # Output: Hello
10) How can you use command-line arguments in a shell script?

Command-line arguments are values provided to a script when it's executed. They can be
accessed within the script using special variables like $1, $2, etc., where $1 represents the first
argument, $2 represents the second argument, and so on.

For Example: If our script name in `example.sh`

#!/bin/bash

echo "Script name: $0"


echo "First argument: $1"
echo "Second argument: $2"

If we run the script with `.example.sh hello_1 hello_2`, it will output:

cli arguments

11) How do you use the for loop to iterate through a list of values?

Create a script name `example.sh`.

#!/bin/bash

fruits=("apple" "banana" "cherry" "date")


for fruit in "${fruits[@]}"; do
echo "Current fruit: $fruit"
done

Explanation:

`fruits=` line creates an array named fruits with four elements: "apple", "banana", "cherry", and
"date".

• for fruit in "${fruits[@]}"; do: This line starts a for loop. Here's what each part means:

• for fruit: This declares a loop variable called fruit. In each iteration of the loop, fruit will
hold the value of the current element from the fruits array.
• "${fruits[@]}": This is an array expansion that takes all the elements from the fruits
array. The "${...}" syntax ensures that each element is treated as a separate item.

• do: This keyword marks the beginning of the loop body.

• echo "Current fruit: $fruit": Inside the loop, this line uses the echo command to display
the current value of the loop variable fruit. It prints a message like "Current fruit: apple"
for each fruit in the array.

• done: This keyword marks the end of the loop body. It tells the script that the loop has
finished.

for loop

12) Write a shell script that calculates the sum of integers from 1 to N using a loop.

Create a script name `example.sh`.

#!/bin/bash

echo "Enter a number (N):"


read N
sum=0
for (( i=1; i<=$N; i++ )); do
sum=$((sum + i))
done
echo "Sum of integers from 1 to $N is: $sum"

Explanation:
The script starts by asking you to enter a number (N) using read. This number will determine
how many times the loop runs.

1. The variable sum is initialized to 0. This variable will keep track of the sum of integers.

2. The for loop begins with for (( i=1; i<=$N; i++ )). This loop structure is used to repeat a
set of actions a certain number of times, in this case, from 1 to the value of N.
3. Inside the loop, these things happen:

• i=1 sets the loop variable i to 1 at the beginning of each iteration.

• The loop condition i<=$N checks if i is still less than or equal to the given number
N.

• If the condition is true, the loop body executes.

• sum=$((sum + i)) calculates the new value of sum by adding the current value of i
to it. This adds up the integers from 1 to the current i value.

4. After each iteration, i++ increments the value of i by 1.

5. The loop continues running until the condition i<=$N becomes false (when i becomes
greater than N).

6. Once the loop finishes, the script displays the sum of the integers from 1 to the entered
number N.

13) Create a script that searches for a specific word in a file and counts its occurrences.

Create a script name `word_count.sh`

#!/bin/bash

echo "Enter the word to search for:"


read target_word
echo "Enter the filename:"
read filename
count=$(grep -o -w "$target_word" "$filename" | wc -l)
echo "The word '$target_word' appears $count times in '$filename'."

Explanation:
• echo "Enter the word to search for:": This line displays a message asking the user to
enter a word they want to search for in a file.

• read target_word: This line reads the input provided by the user and stores it in a
variable named target_word.

• echo "Enter the filename:": This line displays a message asking the user to enter the
name of the file they want to search in.

• read filename: This line reads the input provided by the user and stores it in a variable
named filename.

• count=$(grep -o -w "$target_word" "$filename" | wc -l): This line does the main work of
the script. Let's break it down further:

o grep -o -w "$target_word" "$filename": This part of the command searches for


occurrences of the target_word in the specified filename. The options -o and -w
ensure that only whole word matches are counted.

o |: This is a pipe, which takes the output of the previous command and sends it as
input to the next command.

o wc -l: This part of the command uses the wc command to count the number of
lines in the input. The option -l specifically counts the lines.

o The entire command calculates the count of occurrences of the target_word in


the file and assigns that count to the variable coun

14) Explain the differences between standard output (stdout) and standard error (stderr).

The main difference between standard output (stdout) and standard error (stderr) is as follows:
• Standard Output (stdout): This is the default output stream where a command's regular
output goes. It's displayed on the terminal by default. You can redirect it to a file using >.

• Standard Error (stderr): This is the output stream for error messages and warnings. It's
displayed on the terminal by default as well. You can redirect it to a file using 2>.

15) Explain the concept of conditional statements in shell scripting.

Conditional statements in shell scripting allow us to make decisions and control the flow of our
script based on certain conditions. They enable our script to execute different sets of commands
depending on whether a particular condition is true or false. The primary conditional
statements in shell scripting are the if statement, the elif statement (optional), and the else
statement (optional).

Here's the basic structure of a conditional statement in shell scripting:

if [ condition ]; then
# Commands to execute if the condition is true
elif [ another_condition ]; then
# Commands to execute if another_condition is true (optional)
else
# Commands to execute if none of the conditions are true (optional)
fi

Explanation:

• [ condition ] = Command that evaluates the condition and returns a true (0) or false
(non-zero) exit status.

• then = It is a keyword which indicates that the commands following it will be executed if
the condition evaluates to true.

• elif = (short for "else if") It is a section that allows us to specify additional conditions to
check.

• else = it is a section that contains commands that will be executed if none of the
conditions are true.

• fi = It is a keyword that marks the end of the conditional block.

16) How do you read lines from a file within a shell script?

To read lines from a file within a shell script, we can use various methods, but one common
approach is to use a while loop in combination with the read command. Here's how we can do
it:
#!/bin/bash
file="/home/jayeshkumar/jayesh.txt"
# Check if the file exists
if [ -e "$file" ]; then
while IFS= read -r line; do
echo "Line read: $line"
# Add your processing logic here
done < "$file"
else
echo "File not found: $file"
fi

Explanation:

1. #!/bin/bash: This is the shebang line that specifies the interpreter (/bin/bash) to be used
for running the script.

2. file="/home/jayeshkumar/jayesh.txt": This line defines the variable file and assigns the
full path to the file jayesh.txt in the /home/jayeshkumar directory. Change this path to
match the actual path of the file you want to read.

3. if [ -e "$file" ]; then: This line starts an if statement. It checks if the file specified by the
variable $file exists. The -e flag checks for file existence.

4. while IFS= read -r line; do: This line initiates a while loop that reads lines from the file.

• IFS=: The IFS (Internal Field Separator) is set to an empty value to preserve
leading and trailing spaces.

• read -r line: This reads the current line from the file and stores it in the variable
line.

5. echo "Line read: $line": This line prints the content of the line that was read from the
file. The variable $line contains the current line's content.

6. # Add your processing logic here: This is a placeholder comment where you can add your
own logic to process each line. For example, you might analyze the line, extract
information, or perform specific actions based on the content.

7. done < "$file": This marks the end of the while loop. The < "$file" redirects the content
of the file to be read by the loop.

8. else: If the file does not exist (the condition in the if statement is false), the script
executes the code under the else branch.
9. echo "File not found: $file": This line prints an error message indicating that the
specified file was not found.

10. fi: This line marks the end of the if statement.

reading file

Here , we used `pwd` command to get the path of current directory.

17) Write a function in a shell script that calculates the factorial of a given number.

Here is the script that calculate the factorial of a given number.

#!/bin/bash
# Define a function to calculate factorial
calculate_factorial() {
num=$1
fact=1
for ((i=1; i<=num; i++)); do
fact=$((fact * i))
done
echo $fact
}
# Prompt the user to enter a number
echo "Enter a number: "
read input_num
# Call the calculate_factorial function with the input number
factorial_result=$(calculate_factorial $input_num)
# Display the factorial result
echo "Factorial of $input_num is: $factorial_result"
Explanation:

1. The script starts with the shebang line #!/bin/bash to specify the interpreter.

2. calculate_factorial() is defined as a function. It takes one argument, num, which is the


number for which the factorial needs to be calculated.

3. Inside the function, fact is initialized to 1. This variable will store the factorial result.

4. The for loop iterates from 1 to the given number (num). In each iteration, it multiplies
the current value of fact by the loop index i.

5. After the loop completes, the fact variable contains the calculated factorial.

6. The script prompts the user to enter a number using read.

7. The calculate_factorial function is called with the user-provided number, and the result
is stored in the variable factorial_result.

8. Finally, the script displays the calculated factorial result.

18. Logical Operator in Unix

Logical Operators : They are also known as boolean operators. These are used to perform
logical operations. They are of 3 types:

• Logical AND (&&): This is a binary operator, which returns true if both the operands are
true otherwise returns false.

• Logical OR (||): This is a binary operator, which returns true if either of the operands is
true or if both the operands are true. It returns false only if both operands are false.
• Not Equal to (!): This is a unary operator which returns true if the operand is false and
returns false if the operand is true.

#!/bin/bash

#reading data from the user

read -p 'Enter a : ' a

read -p 'Enter b : ' b

if(($a == "true" & $b == "true" ))

then

echo Both are true.

else

echo Both are not true.

fi

if(($a == "true" || $b == "true" ))

then

echo Atleast one of them is true.

else

echo None of them is true.

fi

if(( ! $a == "true" ))

then

echo "a" was initially false.

else
echo "a" was initially true.

fi

Output:

19. Computation(expr)

What is the 'expr' Command?

expr stands for "expression" and allows for the evaluation of values and returns the result to
standard output. It is particularly useful in scripts for handling both numerical and string data
efficiently. In short, it helps in:

• Basic operations like addition, subtraction, multiplication, division, and modulus on


integers.

• Evaluating regular expressions, string operations like substring, length of strings etc.

Syntax:

$expr expression

Key Options:

• '--version': It is used to show the version information. Syntax:

• $expr --version
Example:

• '--help': It is used to show the help message and exit. Syntax:

• $expr --help
• Example:

'expr' Command Examples

Below are some examples to demonstrate the use of "expr" command:

1. Using expr for basic arithmetic operations :

Example 1: Addition
$expr 12 + 8

Example 2: Multiplication

$expr 12 \* 2

Output

Note: The multiplication operator * must be escaped when used in an arithmetic expression
with 'expr'.

2. Performing operations on variables inside a shell script

Example: Adding two numbers in a script

echo "Enter two numbers"

read x

read y

sum=`expr $x + $y`

echo "Sum = $sum"

Output:
Note: 'expr' is an external program used by Bourne shell. It uses 'expr' external program with
the help of backtick. The backtick(`) is actually called command substitution.

20. Using expr for strings

For String operations

Example 1: Finding length of a string

x=geeks

len=`expr length $x`

echo $len

Output:

Example 2: Finding substring of a string

x=geeks

sub=`expr substr $x 2 3`
#extract 3 characters starting from index 2

echo $sub

Output:

21. Use of positional parameter in unix

A positional parameter is an argument specified on the command line, used to launch the
current process in a shell. Positional parameter values are stored in a special set of variables
maintained by the shell.

Variables which store positional parameters

A typical example of a shell that uses positional parameters is bash. You can use bash on Linux,
BSD (Berkeley Software Distribution), macOS X, and Windows 10.

Consider the following bash command. The command name is mycommand. The command line
has three parameters: one, two, and three four.

mycommand one two "three four"

While mycommand is running, bash provides it with the following shell variables:

Variable name Value

$0 mycommand

$1 one

$2 two
$3 three four

$# 3

$@ one two three four

$* one two three four

22. Here’s a brief explanation of each topic in UNIX system administration, each worth 5 marks:

1. *Username:*

A unique identifier assigned to each user in a UNIX system. It helps distinguish users and
allows for proper access control. Usernames are stored in the /etc/passwd file and are used to
log into the system.

2. *Password:*

A security feature used for authentication. UNIX stores password hashes in /etc/shadow. Users
set their passwords using the passwd command, ensuring secure access to their accounts.

3. *Home Directory:*

A personal space for each user where files and configurations are stored. The home directory
is typically /home/username. It contains user-specific settings and data, enhancing file
organization.

4. *Group ID (GID):*

Identifies the primary group to which a user belongs. UNIX groups help in managing
permissions collectively. The GID is stored in /etc/group and ensures that users have shared
access to resources.

5. *Disk Quota:*
Limits the amount of disk space a user or group can use. Administrators set quotas using
commands like quota and edquota, preventing excessive resource consumption and maintaining
system efficiency.

6. *Terminal:*

A command-line interface that allows users to interact with the UNIX system. Terminals can be
virtual (tty devices) or physical, providing input/output operations for executing commands and
managing processes.

23. A UNIX system administrator plays a crucial role in managing and maintaining UNIX-based
systems to ensure their efficiency, security, and reliability. Here are the essential duties
explained in detail:

1. *Installation and Configuration:*

The administrator is responsible for installing UNIX operating systems and configuring them
according to the organization's requirements. This includes setting up system parameters,
network configurations, and software installations.

2. *System Monitoring and Performance Optimization:*

Regular monitoring of system performance is essential to ensure smooth operation.


Administrators use tools like top, vmstat, and iostat to analyze system resource usage and
optimize performance by adjusting configurations or upgrading hardware.

3. *User and Account Management:*

Managing user accounts involves creating, modifying, and deleting users, setting permissions,
and ensuring secure access. Commands like useradd, passwd, and groupmod help in managing
user authentication and access control.

4. *Security Management:*
Ensuring system security is a top priority. Administrators implement firewalls, configure access
controls, apply security patches, and monitor logs for suspicious activities using tools like
iptables, fail2ban, and auditd.

5. *Backup and Recovery:*

Regular backups are crucial to prevent data loss. Administrators schedule automated backups
using tools like tar, rsync, and cron, ensuring quick recovery in case of system failures.

6. *Software and Patch Management:*

Keeping the system updated with the latest software and security patches is essential.
Administrators use package managers like apt, yum, or pkg to install and update software
efficiently.

7. *Troubleshooting and Issue Resolution:*

Diagnosing and resolving system issues is a key responsibility. Administrators analyze logs,
debug errors, and use troubleshooting commands like dmesg, journalctl, and strace to identify
and fix problems.

8. *Network Configuration and Management:*

Configuring network settings, managing IP addresses, and ensuring connectivity are vital tasks.
Administrators use commands like ifconfig, netstat, and ping to monitor and troubleshoot
network-related issues.

9. *Disk and File System Management:*

Managing disk space, partitions, and file systems ensures efficient storage utilization.
Commands like df, du, fdisk, and mkfs help in maintaining disk health and optimizing storage.

10. *Automation and Scripting:*


Automating repetitive tasks using shell scripting improves efficiency. Administrators write
scripts using Bash, Python, or Perl to automate system maintenance, monitoring, and reporting.

24. In UNIX, *starting* and *shutdown* processes are crucial for system management. Here’s a
brief explanation:

### *Starting UNIX:*

1. *Boot Process:* When the system is powered on, the bootloader (like GRUB) loads the UNIX
kernel into memory.

2. *Kernel Initialization:* The kernel initializes hardware components and mounts the root
filesystem.

3. *System Initialization:* The system runs startup scripts (/etc/init.d or systemd services) to
configure network settings, user sessions, and background processes.

4. *Login Prompt:* Once initialization is complete, the system presents a login prompt for users
to access the system.

### *Shutdown in UNIX:*

1. *Shutdown Command:* The shutdown command safely stops the system, notifying users and
terminating processes before powering off.

- shutdown -h now → Immediately shuts down the system.

- shutdown -r now → Reboots the system.

- shutdown -c → Cancels a scheduled shutdown.

2. *Halt and Poweroff:*

- halt → Stops the system but keeps it powered on.

- poweroff → Completely turns off the system.

3. *Reboot:*

- reboot → Restarts the system.

You might also like