0% found this document useful (0 votes)
3 views16 pages

Unit 3 Linux

Unit 3 covers shell scripting in Linux, detailing the creation and execution of scripts, the use of shell metacharacters and operators, and control flow structures. It explains how to use logical operators, condition testing commands, and perform arithmetic operations within scripts. The document provides practical examples and syntax for various scripting tasks, enhancing the reader's understanding of Linux shell scripting.

Uploaded by

vaishnavbhavna17
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 views16 pages

Unit 3 Linux

Unit 3 covers shell scripting in Linux, detailing the creation and execution of scripts, the use of shell metacharacters and operators, and control flow structures. It explains how to use logical operators, condition testing commands, and perform arithmetic operations within scripts. The document provides practical examples and syntax for various scripting tasks, enhancing the reader's understanding of Linux shell scripting.

Uploaded by

vaishnavbhavna17
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/ 16

Unit 3 : Shell Scripting in Linux

3.1 Creating and Executing Shell Scripts (nano, vi, ./script.sh)

3.2 Shell Metacharacters and Operators

3.2.1 Filename Expansion (wildcards: *, ?, [])

3.2.2 Input/Output Redirection (>, >>, <)

3.2.3 Pipes (|)

3.2.4 Command Substitution ($(...), ...)

3.3 Control Flow Structures (if-else, case, for, while, until)

3.4 Logical Operators (&&, ||, !)

3.5 test and [ ] command for Condition Testing (file, numeric, string)

3.6 Arithmetic Operations (expr, $(( )))

3.1 Creating and Executing Shell Scripts (nano, vi, ./script.sh)

3.1 Creating and Executing Shell Scripts (nano, vi, ./script.sh)

A shell script is a file containing a series of Linux/Unix commands written in plain text, which
can be executed together as a program.

Steps to Create and Execute a Shell Script

Step 1: Create a Script File

You can create a shell script using a text editor like nano or vi.

Using nano editor:

bash

nano script.sh

is opens the nano editor.

Type your script (example below), then press CTRL + O to save, and CTRL + X to exit.
Using vi editor:

vi script.sh

• Press i to enter insert mode.

• Write your script (example below).

• Press Esc, then type :wq and hit Enter to save and exit.

• Step 2: Write a Simple Script


• Here is a basic shell script example:
• bash

• #!/bin/bash
• # This is a comment
• echo "Hello, World!"
• date
• • #!/bin/bash is called the shebang. It tells the system to use the bash shell to
interpret the script.
• • echo and date are sample commands.
• Step 3: Make the Script Executable
• Before executing the script, you need to give it execute permissions:
• bash
• chmod +x script.sh
Step 4: Run the Script

You can run the script in two ways:

1. Using relative path:

bash

CopyEdit

./script.sh

2. Using absolute path:

bash

CopyEdit

/home/username/path/to/script.sh

num=5

if [ $num -gt 0 ]; then

echo "Positive number"


else

echo "Non-positive number"

fi

Task Command

Create with nano nano script.sh

Create with vi vi script.sh

CTRL + O, then CTRL + X

Save in nano

Save in vi Esc, then :wq

Make executable chmod +x script.sh

Run the script ./script.sh

3.2 Shell Metacharacters and Operators

In a Linux shell, metacharacters and operators are special symbols used to control how
commands behave, manage input/output, or perform logic.

A. Shell Metacharacters

Metacharacters are symbols with special meanings to the shell. They’re not treated as plain
text.

Metacharacter Description Example

Matches zero or more characters


* ls *.txt → matches all .txt files
(wildcard)

? Matches exactly one character ls file?.txt

ls file[1-3].txt → file1.txt to
[] Matches a range or set of characters
file3.txt

'' Single quotes preserve literal value echo 'Today is $DATE'


Metacharacter Description Example

"" Double quotes allow variable expansion echo "Today is $DATE"

`` Command substitution (old way) echo `date`

$() Command substitution (modern way) echo $(date)

\ Escape the next character echo \$HOME

; Separate multiple commands in one line date; whoami

Run next command only if previous


&& mkdir test && cd test
succeeds

` `

# Comment symbol # This is a comment

B. Shell Operators

1. Input/Output Redirection

Operator Description Example

> Redirect output to a file (overwrite) ls > filelist.txt

>> Append output to a file echo "Done" >> logfile.txt

< Take input from a file wc -l < file.txt

2> Redirect stderr command 2> error.log

&> Redirect stdout and stderr command &> output.log

3. Background Execution

Description Example
Operator

B R1& Run command in the background sleep 60 &

. 4 Command Grouping
Operator Description Example

(cd /tmp &&


() Run commands in a subshell ls)
Operator Description Example

Run commands in current shell (no { cd /tmp; ls; }


{}
subshell)

3.2.1 Filename Expansion (Wildcards: *, ?, []) in Linux

Filename expansion using wildcards allows you to match multiple files or directories without
typing their full names. This feature is part of globbing in the shell.

ls *.txt # Lists all files ending with .txt

ls file* # Lists all files starting with "file"

ls * # Lists all files and directories in the current folder

2. Question Mark ?

• Matches exactly one character.

• Used when you want to match filenames with a specific number of characters.

Examples:

ls ?.txt # Matches a.txt, b.txt (any single character before .txt)

ls file?.sh # Matches file1.sh, fileA.sh (but not file12.sh)

3. Square Brackets []

• Matches any one character enclosed within the brackets.

• Can include:

o A list of characters: [abc]

o A range of characters: [a-z] or [0-9]

Examples:

ls file[123].txt # Matches file1.txt, file2.txt, file3.txt

ls file[a-c].txt # Matches filea.txt, fileb.txt, filec.txt


ls [A-Z]*.sh # Matches any file starting with an uppercase letter and ending with .sh

ls data[1-3]?.csv # Matches data11.csv, data22.csv, data33.csv (where ? matches one more


character)

Pipes (|) in Linux

A pipe (|) is a powerful feature in Linux that allows combining multiple commands, passing
the output of one command as input to another. It's a key part of Unix/Linux philosophy:
"Do one thing well, and connect programs together."

Syntax

bash

CopyEdit

command1 | command2

• command1: produces output (stdout)

• command2: receives input from command1 (stdin)

Example 1: Basic Use

bash

CopyEdit

ls -l | grep "Aug"

• Lists all files with detailed info, then filters lines that contain "Aug".

Example 2: Count Files in a Directory

bash

CopyEdit

ls | wc -l
• ls: lists files

• wc -l: counts the number of lines (i.e., number of files)

Example 3: Find and Sort

bash

CopyEdit

ps aux | sort -rk 3 | head -5

• Shows top 5 processes consuming the most CPU.

o ps aux: lists all running processes

o sort -rk 3: sorts by CPU usage (3rd column) in reverse

o head -5: shows top 5

Key Notes

• Pipes only work with standard input/output.

• Cannot pass stderr (error messages) through a pipe unless redirected using 2>&1.

Try This

bash

CopyEdit

cat /etc/passwd | cut -d: -f1 | sort

• Extracts and sorts all usernames from the system's password file.

Control Flow Structures (if-else, case, for, while, until)

If Statements

If statements allow you to execute code based on a condition. If the condition is true, the
code block will run.

The condition is enclosed in square brackets [ ] and the statement ends with fi, which
is if spelled backward, marking the end of the if block.

# Basic if statement
num=15
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
fi

1. if-else

2. If...Else Statements
If...else statements provide a way to execute one block of code if a
condition is true and another block if it is false.

The else keyword introduces the alternative block, and the statement
ends with fi.

if [ condition ]; then
# commands if condition is true
elif [ another_condition ]; then
# commands if second condition is true
else
# commands if no condition is true
fi
script

# If...else statement
num=8
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is 10 or less"
fi

num=10
if [ $num -gt 0 ]; then
echo "Positive"
else
echo "Non-positive"
fi
Using Loops
For Loops
For loops allow you to iterate over a list of items or a range of numbers. They are
useful for repeating tasks a specific number of times.
The for keyword is followed by a variable name, a range of values, and a do keyword,
which marks the start of the loop block.

Example: For Loop


# For loop example
for i in {1..5}; do
echo "Iteration $i"
done

While Loops

While loops execute a block of code as long as a specified condition is true.


They are useful for tasks that need to repeat until a certain condition changes.
The condition is enclosed in square brackets [ ], and the loop ends with done.
Example: While Loop

# While loop example


count=1
while [ $count -le 5 ]; do
echo "Count is $count"
((count++))
done

Until Loops
Until loops are similar to while loops, but they execute until a specified condition
becomes true.
The condition is enclosed in square brackets [ ], and the loop ends with done.
Example: Until Loop
# Until loop example
count=1
until [ $count -gt 5 ]; do
echo "Count is $count"
((count++))
done
Break and Continue
Break and continue statements are used to control loop execution. break exits the
loop, while continue skips to the next iteration.
These statements are typically used inside conditional blocks to alter the flow of the
loop.
Example: Break and Continue
# Break and continue example
for i in {1..5}; do
if [ $i -eq 3 ]; then
continue
fi
echo "Number $i"
if [ $i -eq 4 ]; then
break
fi
done

3. Elif Statements
Elif statements allow you to check multiple conditions in sequence. If
the first condition is false, the next one is checked.
The elif keyword stands for "else if," and the statement still ends
with fi.

Nested If Statements
Nested if statements allow you to place an if statement inside another if statement,
enabling more complex logic.
Each if block must be closed with its own fi.
Example: Nested If Statement
# Nested if statement
num=5
if [ $num -gt 0 ]; then
if [ $num -lt 10 ]; then
echo "Number is between 1 and 9"
fi
fi
Nested Loops

Nested loops allow you to place one loop inside another, enabling more complex
iteration patterns.
Each loop must be closed with its own done.
Example: Nested Loops
# Nested loops example
for i in {1..3}; do
for j in {1..2}; do
echo "Outer loop $i, Inner loop $j"
done
done

3.4 Logical Operators in Linux (&&, ||, !)


Logical operators in Linux are commonly used in shell scripting and command chaining.
These operators are used to control execution flow based on the success or failure of
commands.

&& (AND Operator)

• Executes the second command only if the first command succeeds (i.e., returns exit
status 0).

• It is used to chain commands where the second depends on the success of the first.

Syntax:

bash

command1 && command2

mkdir new_folder && cd new_folder

• cd new_folder will execute only if mkdir new_folder is successful.

|| (OR Operator)

• Executes the second command only if the first command fails (i.e., returns non-zero
exit status).

• Used as a fallback when the first command fails.

command1 || command2
Example:

rm file.txt || echo "file.txt does not exist"

• If rm file.txt fails (e.g., file not found), it prints the message.

! (NOT Operator)

• Reverses the exit status of a command.

• If a command succeeds (exit status 0), ! makes it fail (exit status 1) and vice versa.

! command

Example:

! grep "hello" file.txt

• Succeeds only if "hello" is not found in file.txt.

Combined Example:

[ -f myfile.txt ] && echo "File exists" || echo "File does not exist"

• If myfile.txt exists: prints "File exists"

• Otherwise: prints "File does not exist"

Summary Table:

Operator Meaning Executes Second If...

&& Logical AND First command succeeds

` `

! Logical NOT (negation) Reverses command’s exit status

test and [ ] Command in Linux


Used for Condition Testing: File, Numeric, String)

In shell scripting and command-line usage, the test command and its synonym [ ] are
used to evaluate conditions such as:

• File types and permissions

• Numeric comparisons
• String comparisons

They return:

• 0 (true) if the condition is satisfied

• 1 (false) if the condition is not satisfied

• 1. Basic Syntax
• test condition
• # OR
• [ condition ]

Note: There must be a space between brackets and the condition: [ condition ], not
[condition]

2. File Conditions

num=10

[ $num -gt 5 ] && echo "Number is greater than 5"

4. String Conditions

Expression Meaning

str1 = str2 Strings are equal

str1 != str2 Strings are not equal

-z string String is empty

-n string String is not empty

Example:

name="Linux"

[ "$name" = "Linux" ] && echo "Matched"

5. Avoid Common Mistakes

• Always quote variables in conditions to avoid errors:

[ "$var" = "value" ] # Safe

Use spaces properly:

[ "$a" -gt 5 ] # Correct


[ "$a"-gt5 ] # Incorrect

6. Combined Conditions

AND (-a) and OR (-o) inside test

[ "$a" -gt 5 -a "$b" -lt 10 ] # AND

[ "$a" -gt 5 -o "$b" -lt 10 ] # OR

Tip: Better to use [[ ]] for complex conditions:

[[ $a -gt 5 && $b -lt 10 ]] # Safer and more flexible

Example Shell Script Using All Types

#!/bin/bash

file="test.txt"

num=20

name="Linux"

# File test

[ -e "$file" ] && echo "File exists"

# Numeric test

[ $num -ge 10 ] && echo "Number is greater or equal to 10"

# String test

[ "$name" = "Linux" ] && echo "Welcome to Linux"

Arithmetic Operations in Linux


(Using expr and $(( )))
In Linux shell (especially Bash), arithmetic operations can be done using:

1. expr Command

• expr evaluates integer expressions.

• Each element (operator, operand) must be separated by spaces.

• Returns result to stdout (prints it).

• It supports: +, -, *, /, %, comparison operators.

Syntax:

expr operand1 operator operand2

Examples:

expr 5 + 3 #8

expr 10 - 2 #8

expr 4 \* 2 # 8 (Note: * must be escaped with \)

expr 20 / 5 #4

expr 9 % 4 #1

Always escape * (multiplication): \*

Assigning result to variable:

$(( expression ))

Examples:

a=5

a=$(expr $a + 1)

echo $a #6

Using $(( )):

a=5

a=$(( a + 1 ))
echo $a #6

Comparison Table

Feature expr $(( ))

Syntax Verbose, older Cleaner, modern

Multiplication Must escape * (\*) No need to escape *

Supports variables Yes Yes

Integer-only? Yes Yes

Preferred in Bash (useful for POSIX shell)

Tip:

For floating-point math, use bc (since both expr and $(( )) handle only integers):

echo "scale=2; 5 / 2" | bc # 2.50

Example Script

#!/bin/bash

a=8

b=4

# Using expr

sum=$(expr $a + $b)

echo "Sum using expr: $sum"

# Using $(( ))

diff=$(( a - b ))

echo "Difference using \$(( )): $diff"

You might also like