Unit 3. Shell Programming

INDEX

  • 3.1. Screen Editor (vi)
  • 3.2. Environmental & user defined variables
  • 3.3. Conditional Execution
  • 3.4. Arithmetic expression evaluation
  • 3.5. Control Structure
  • 3.6. Redirection
  • 3.7. Background process & priorities of process, Batch Process
  • 3.8. Argument Processing & Shells interpretation

🖥️ Shell Programming – Screen Editor (vi) in Detail.

🔹 What is vi?

  • The vi editor (short for visual editor) is one of the oldest and most powerful text editors in Unix/Linux systems.
  • It is used primarily for editing configuration files, writing shell scripts, and managing system-related files in a command-line environment.
  • It comes pre-installed on almost all Unix-like systems, making it an essential tool for system administrators and developers working in shell environments.

🔹 Features of vi Editor

  • ✅ Available on all Unix/Linux systems
  • ✅ Lightweight and fast
  • ✅ Powerful text editing commands
  • ✅ Does not rely on GUI
  • ✅ Enables programming directly in terminal
  • ✅ Syntax highlighting (in vim, an enhanced version)

🔹 Modes of vi Editor

vi works in three primary modes:
Mode Description
Command Mode Default mode. Allows you to navigate and issue editing commands.
Insert Mode Enables text entry and modification.
Last Line Mode (Ex Mode) Used for file operations like saving, quitting, and searching. Starts with :.

🔹 Switching Between Modes

Action Key
Enter Insert Mode i, a, or o
Return to Command Mode Esc
Enter Last Line Mode :

🔹 Common vi Commands

Command Description
i Insert text before the cursor
a Append text after the cursor
o Open a new line below and insert
Esc Exit insert mode
:w Save the file
:q Quit the editor
:wq Save and quit
:q! Quit without saving
dd Delete the current line
yy Copy (yank) the current line
p Paste the copied content
/word Search for a word
n Find the next occurrence

🔹 Example Workflow

  1. Open a file: vi myscript.sh
  2. Press i to enter Insert Mode and start typing your shell script.
  3. Press Esc to go back to Command Mode.
  4. Type :wq to save and exit the editor.

🔹 vi vs vim

  • vi is the traditional editor.
  • vim (Vi Improved) is an enhanced version that offers additional features like syntax highlighting, undo tree, visual mode, etc.
You can install vim using:
sudo apt install vim # for Debian/Ubuntu
sudo yum install vim # for CentOS/Red Hat

🐚 Shell Programming: Environmental & User-Defined Variables

🔹 What Are Shell Variables?

  • In shell programming, variables are used to store data such as strings, numbers, or file names.
  • These variables help automate tasks and make scripts more dynamic and reusable.

There are two main types of variables in shell programming:

1. Environmental Variables

  • Environmental variables are system-wide variables that are defined by the operating system or shell and are used to configure the shell’s behavior or to pass information to programs.

✳️ Key Characteristics:

  • Available to all child processes.
  • Typically defined in startup files like .bashrc, .bash_profile, or /etc/profile.
  • Can be viewed or modified using env, printenv, set, or export.

🔍 Examples:

Variable Description
PATH Directories the shell searches for executable files
HOME Path of the current user’s home directory
USER Username of the currently logged-in user
SHELL Path of the current user’s default shell
PWD Present working directory
LANG Language setting for the system

🔧 Example Usage:

echo $USER # Displays the current username
echo $PATH # Shows the directories in PATH

2. User-Defined Variables

These are variables that you create in your shell session or scripts.

✳️ Key Characteristics:

  • Local to the script or terminal session.
  • Can be named using letters, numbers, and underscores (no spaces).
  • Assignment is done without the $ symbol.
🔍 Example: name=”Hardik”
echo $name # Output: Hardik
#!/bin/bash
greeting=”Hello”
user=”Hardik”
echo “$greeting, $user! Welcome to Shell Programming.”

🌐 Exporting User Variables to Environment

If you want your custom variable to be available to child processes, use export.

export name=”Hardik”

🐚 Shell Programming: Conditional Execution.

  • In shell scripting, conditional execution allows you to control the flow of a script based on whether certain conditions are true or false.
  • This is useful when you want your script to perform different actions depending on user input, file states, or system conditions.

✅ 1. The if Statement

The if statement checks a condition and executes a block of code if the condition evaluates to true.

🔹 Syntax:

if [ condition ]
then
# commands to execute if condition is true
fi
🔹 Example:
age=20
if [ $age -ge 18 ]
then
echo “You are eligible to vote.”
fi

✅ 2. if-else Statement.

Executes one block if the condition is true, and another if it’s false.

🔹 Syntax:

if [ condition ]
then
# if true
else
# if false
fi
🔹 Example:
number=5
if [ $number -gt 10 ]
then
echo “Number is greater than 10”
else
echo “Number is 10 or less”
fi

✅ 3. if-elif-else Ladder

Allows checking multiple conditions in sequence.

🔹 Syntax:

if [ condition1 ]
then
# commands
elif [ condition2 ]
then
# commands
else
# default commands
fi

🔹 Example:

marks=75
if [ $marks -ge 90 ]
then
echo “Grade: A”
elif [ $marks -ge 75 ]
then
echo “Grade: B”
else
echo “Grade: C”
fi

✅ 4. Using test or [ ]

Shell uses test or square brackets [ ] to evaluate conditions. Common comparisons:
Comparison Meaning
-eq Equal
-ne Not equal
-gt Greater than
-lt Less than
-ge Greater than or equal
-le Less than or equal
== String equal
!= String not equal
-z String is empty
-n String is not empty

✅ 5. Conditional Execution with && and ||

These operators can be used to run commands based on the success or failure of previous commands.
Operator Description
command1 && command2 command2 runs only if command1 succeeds

🔹 Example:

  • mkdir new_folder && echo “Directory created successfully”.
  • rm non_existent.txt || echo “File does not exist”

✅ 6. Nested if Statements

An if inside another if.
if [ $a -gt 0 ]
then
if [ $a -lt 100 ]
then
echo “a is between 0 and 100”
fi
fi

🔢 Arithmetic Expression Evaluation in Linux Shell.

  • Arithmetic operations are a core part of shell scripting. In Linux, especially using the Bash shell, you can perform basic arithmetic like addition, subtraction, multiplication, division, and modulus using various methods.
  • However, keep in mind that Bash only handles integer arithmetic by default.

✅ Common Methods for Arithmetic Evaluation.

1. Using (( )) (Arithmetic Expansion) :-

  • The (( )) syntax is widely used for arithmetic evaluation.
  • It allows direct arithmetic without needing command substitution or extra spacing.
Example:
  • a=10
    b=5
    (( result = a + b ))
    echo $result # Output: 15
In conditions:
  • if (( a > b )); then
    echo “a is greater than b”
    fi
  • Note: You do not need to use $ for variables inside (( )).

2. Using let Command.

  • The let command is used to evaluate arithmetic expressions.
  • It works similarly to (( )).
Example:
  • a=7
    b=3
    let sum=a+b
    echo $sum # Output: 10
You can also use quotes:
  • let “sum = a * b”

3. Using expr Command.

  • The expr command is used to evaluate expressions but requires careful formatting and spacing.

Example:

  • a=20
    b=4
    result=$(expr $a / $b)
    echo $result # Output: 5
Important: All elements (operands and operator) must be separated by spaces.

4. Using bc (Basic Calculator)

  • Bash does not support floating-point arithmetic directly.
  • If you need decimals or more complex math, use the bc command-line calculator.
  • Example (floating-point division):
  • echo “scale=2; 10 / 3” | bc # Output: 3.33
scale=2 sets the number of decimal places.

🔣 Supported Operators in Arithmetic Expressions.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division (integer)
% Modulus (remainder)
** Exponentiation (not in all shells)

✅ Example Shell Script.

  • #!/bin/bash
    a=12
    b=5
    echo “Addition: $((a + b))”
    echo “Subtraction: $((a – b))”
    echo “Multiplication: $((a * b))”
    echo “Division: $((a / b))”
    echo “Modulus: $((a % b))”
Output:
  • Addition: 17
    Subtraction: 7
    Multiplication: 60
    Division: 2
    Modulus: 2

🧠 Summary

  • Use (( )) or let for easy and clean integer arithmetic.
  • Use expr for POSIX compatibility (older systems).
  • Use bc for advanced and floating-point calculations.
  • Always use proper spacing with expr.
  • Bash cannot natively handle floating points—bc is essential for that.

🔁 Control Structures in Shell Programming (Bash).

  • Control structures allow shell scripts to make decisions, repeat tasks, and control the flow of execution.
  • These structures are essential to make scripts dynamic and functional, similar to logic used in traditional programming languages.

🔹 1. Conditional Statements (if, if-else, if-elif-else)

  • Used to execute commands based on whether a condition is true or false.

✅ Basic if statement:

  • if [ condition ]
    then
    # commands if condition is true
    fi

if-else example:

  • if [ $num -gt 0 ]
    then
    echo “Positive number”
    else
    echo “Not a positive number”
    fi

if-elif-else example:

  • if [ $num -gt 0 ]
    then
    echo “Positive”
    elif [ $num -lt 0 ]
    then
    echo “Negative”
    else
    echo “Zero”
    fi

🔹 2. Case Statement (Switch-like logic)

The case statement is used to match a value against multiple patterns.

✅ Example:

  • echo “Enter a letter:”
    read letter
    case $letter in a|A)
    echo “Vowel A”;; e|E)
    echo “Vowel E”;;i|I)
    echo “Vowel I”;;o|O)
    echo “Vowel O”;;u|U)
    echo “Vowel U”;;*)
    echo “Not a vowel”;;
    esac

🔹 3. Loops in Shell

Loops are used to repeat a set of commands until a condition is met or for a fixed number of times.

for Loop

  • for i in 1 2 3 4 5
    do
    echo “Number: $i”
    done
You can also use C-style syntax:
  • for ((i=0; i<5; i++))
    do
    echo “Iteration: $i”
    done

while Loop

Runs as long as the condition is true.
  • count=1
    while [ $count -le 5 ]
    do
    echo “Count is $count”
    ((count++))
    done

until Loop

Runs until the condition becomes true (opposite of while).
  • count=1
    until [ $count -gt 5 ]
    do
    echo “Count is $count”
    ((count++))
    done

🔹 4. Break and Continue

  • break – Exits the loop immediately.
  • continue – Skips the current iteration and moves to the next.

✅ Example:

  • for i in {1..10}
    do
    if [ $i -eq 5 ]; then
    continue # skip 5
    fi
    echo $i
    done

🔹 5. Nested Structures

You can nest if, loops, and case statements within each other.

✅ Example:

  • for i in {1..5}
    do
    if [ $i -eq 3 ]
    then
    echo “Special number: $i”
    else
    echo “Normal number: $i”
    fi
    done

🧠 Summary Table.

Structure Use Case
if Check if a condition is true
if-else Execute one block if true, another if false
elif Check multiple conditions sequentially
case Match variable against multiple patterns
for Loop over a range or list
while Loop while condition is true
until Loop until condition is true
break Exit loop
continue Skip current iteration

Redirection in Shell Programming – Detailed Explanation.

  • Redirection in shell programming allows the user to change the standard input/output of commands.
  • By default, every command takes input from the keyboard (stdin) and sends output to the screen (stdout).
  • With redirection, you can modify this behavior to read input from a file or send output to a file, or even. redirect error messages.

🔁 Types of Redirection.

1. Output Redirection (> and >>)

Used to send the output of a command to a file instead of the screen.
  • :Redirects output to a file. If the file exists, it is overwritten.

  • echo “Hello” > file.txt
  • >>: Appends the output to the end of the file without overwriting.
  • echo “World” >> file.txt

2. Input Redirection (<)

Used to provide input to a command from a file instead of the keyboard.
  • wc < file.txt
This will count words in file.txt.

3. Error Redirection (2>, 2>>).

Redirects error messages (stderr) to a file.
2>: Redirects error output to a file, replacing it if it exists.
  • ls nonexist.txt 2> error.log
2>>: Appends error output to an existing file.
  • ls anotherfile 2>> error.log

4. Combining stdout and stderr.

  • Redirect both standard output and standard error to the same file:
  • command > output.txt 2>&1
Alternatively, a shorthand in Bash:
  • command &> output.txt

5. Here Document (<<).

Allows you to provide multiple lines of input to a command directly within the script.
  • cat << END
    This is line 1
    This is line 2
    END

6. Here String (<<<)

Redirects a single line of input directly into a command.
  • grep “hello” <<< “hello world”

🔍 Summary of Symbols.

Symbol Description
> Redirect standard output (overwrite)
>> Redirect standard output (append)
< Redirect standard input
2> Redirect standard error (overwrite)
2>> Redirect standard error (append)
&> Redirect both stdout and stderr
<< Here document (multi-line input)
<<< Here string (single-line input)

🧠 Shell Programming: Background Process, Priorities, and Batch Process.

🔄 1. Background Processes.

  • In a Unix/Linux shell, when you run a command, it typically runs in the foreground — meaning you have to wait for it to finish before you can run another command.
  • A background process allows the shell to run other commands without waiting for the current one to complete.

✅ How to Run a Process in Background

To run a command in the background, add an ampersand (&) at the end:
  • long_running_command &

This will:

  • Start the process in the background.
  • Return control to the shell immediately.
  • Display a job ID and process ID (PID) for reference.

🔧 Managing Background Processes

  • jobs: Lists all current background jobs.
  • fg: Brings the most recent background job to the foreground.
  • fg %n: Brings job number n to the foreground.
  • bg: Resumes a suspended job in the background.
  • kill PID: Terminates a process by its Process ID.

⚙️ 2. Process Priorities.

  • Every running process in Unix/Linux has a priority, which determines how much CPU time it gets.
  • This priority is managed by a value called the “nice value”.

📌 What is “Nice”?

  • “Nice” is a user-space way of suggesting how nice a process should be to other processes.
  • Range: -20 (highest priority) to 19 (lowest priority).
  • Default nice value is 0.

✅ Commands:

  • nice: Start a process with a specified nice value.
  • nice -n 10 myscript.sh
renice: Change the priority of a running process.
Note: Only the superuser (root) can increase priority (i.e., use negative nice values).

📦 3. Batch Processing.

  • A batch process refers to running a group of non-interactive tasks automatically without user intervention.
  • These tasks are usually scheduled to run at specific times or under specific conditions.

✅ Characteristics:

  • Executes jobs one after another in the order they’re listed.
  • Often used for processing large volumes of data or performing regular maintenance tasks.

🔧 Tools for Batch Processing:

  • cron: Schedules jobs to run periodically (e.g., hourly, daily).
    Example crontab entry:
  • 0 2 * * * /home/user/backup.sh
at: Schedules a job to run once at a specified time.
  • echo “myscript.sh” | at 10:30
batch: Runs jobs when system load is low.
  • echo “heavy_job.sh” | batch

📋 Summary Table

Feature Description
Background Process Runs without blocking the terminal; started with &
Process Priority Controlled via "nice" values; lower value = higher priority
Batch Processing Non-interactive, scheduled execution of tasks using cron, at, or batch

🧠 Argument Processing & Shell Interpretation in Shell Programming.

🧩 What is Argument Processing?

  • Argument processing refers to the way a shell script accepts input values (arguments) when the script is executed.
  • These arguments allow scripts to be dynamic and flexible based on user input or data passed from other programs.

📌 Passing Arguments to a Shell Script

When running a shell script, you can pass arguments directly after the script name:

  • ./script.sh arg1 arg2 arg3

Inside the script, these arguments can be accessed using special variables:

 
Variable Description
$0 Name of the script
$1 First argument
$2 Second argument
... ...
$# Number of arguments passed
$@ All arguments as separate words
$* All arguments as a single word
  • #!/bin/bashecho “Script Name: $0″echo “First Argument: $1″echo “Second Argument: $2″echo “Total Arguments: $#”
Run it like this:
  • ./my_script.sh hello world
Output:
  • Script Name: ./my_script.sh
    First Argument: hello
    Second Argument: world
    Total Arguments: 2

⚙️ What is Shell Interpretation?

When you run a shell script, the shell (like bash, sh, zsh) interprets the commands written inside the script, line by line.

🔄 Interpretation Process:

  1. Tokenizing – The shell breaks the command line into words (tokens).
  2. Variable Substitution – Variables like $1, $USER, etc., are replaced with their values.
  3. Command Substitution – Commands inside $(...) or backticks `...` are executed and replaced by their output.
  4. Globbing – Wildcard characters like *, ? are expanded to matching filenames.
  5. Redirection>, <, >>, 2> direct the input/output.
  6. Execution – After interpretation, the shell runs the command.

✅ Example:

  • #!/bin/bash
    FILE=”sample.txt”
    echo “The content of $FILE is:”
    cat “$FILE”

📌 Commonly Used Shells.

Shell Description
sh Original Bourne shell
bash Bourne Again Shell – most common, with extended features
zsh Z Shell – user-friendly with rich customization
ksh Korn Shell – combines features of sh and csh

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.