7th Chapter Unix
7th Chapter Unix
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.
• 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.
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.
• Make sure the script file has executable permissions using the chmod command:
chmod +x myscript.sh
./myscript.sh
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".
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?
For example:
#!/bin/bash
# Assigning a value to a variable
name="Jayesh"
age=21
echo $name $age
Explanation:
• 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.
#!/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.
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.
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.
#!/bin/bash
cli arguments
11) How do you use the for loop to iterate through a list of values?
#!/bin/bash
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.
• 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.
#!/bin/bash
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:
• The loop condition i<=$N checks if i is still less than or equal to the given number
N.
• 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.
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.
#!/bin/bash
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 |: 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.
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>.
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).
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.
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.
reading file
17) Write a function in a shell script that calculates 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.
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.
7. The calculate_factorial function is called with the user-provided number, and the result
is stored in the variable factorial_result.
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
then
else
fi
then
else
fi
if(( ! $a == "true" ))
then
else
echo "a" was initially true.
fi
Output:
19. Computation(expr)
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:
• Evaluating regular expressions, string operations like substring, length of strings etc.
Syntax:
$expr expression
Key Options:
• $expr --version
Example:
• $expr --help
• Example:
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'.
read x
read y
sum=`expr $x + $y`
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.
x=geeks
echo $len
Output:
x=geeks
sub=`expr substr $x 2 3`
#extract 3 characters starting from index 2
echo $sub
Output:
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.
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.
While mycommand is running, bash provides it with the following shell variables:
$0 mycommand
$1 one
$2 two
$3 three four
$# 3
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:
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.
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.
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.
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.
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.
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.
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.
24. In UNIX, *starting* and *shutdown* processes are crucial for system management. Here’s a
brief explanation:
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.
1. *Shutdown Command:* The shutdown command safely stops the system, notifying users and
terminating processes before powering off.
3. *Reboot:*