Bash Scripting
What is the 1st Line in a Shell Script?
The first line in a shell script is typically the shebang (#!), followed by the path to the shell
interpreter. For example:
#!/bin/bash
This line tells the operating system which interpreter to use to execute the script. In this
case, it specifies /bin/bash as the interpreter What Happens If You Don't Include
the 1st Line?
1. Default Interpreter Used:
• If you don't include the shebang line, the script will be executed using the default
shell of the environment (e.g., /bin/sh on most systems).
• This might cause unexpected behavior if your script uses features specific to
another shell (e.g., bash or zsh).
2. Portability Issues:
• Without the shebang, the script may behave differently on systems
with different default shells, leading to portability problems.
3. Error for Non-Shell Files:
• If the file isn’t recognized as a shell script, it may fail to execute
altogether, especially if invoked without an interpreter.
Why Is the 1st Line Important?
• Ensures compatibility: Specifies the exact interpreter, avoiding
reliance on the system default.
• Improves portability: Makes the script runnable on any system
with the specified interpreter.
• Reduces errors: Prevents syntax errors or unexpected behavior
when using shell-specific features.
Example: #!/bin/bash
echo "Hello, World!"
save and exit
1 Gmail id : opskillsup@[Link] Contact :7483-537- 551
how to execute shell script
./[Link] or bash [Link] Steps
to Write a Shell Script
1. Create a New File:
Use a text editor to create the script file. For example:
Vi [Link]
2. Add the Shebang Line:
The first line of the script should specify the shell interpreter (e.g., bash, sh, or
zsh)
#!/bin/bash
This ensures that the script runs with the correct interpreter
3. Write the Script Logic:
Add the commands you want the script to execute. For example
#!/bin/bash echo
"Hello, World!"
4. Save the File:
Save the file with a .sh extension for clarity (e.g., [Link]).
5. Make the Script Executable:
Use the chmod command to give the script execute permissions
chmod +x [Link]
6. Run the Script:
Execute the script by specifying the path - ./[Link]
2 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Example Shell Script
#!/bin/bash echo "Welcome to Shell Scripting!" date
Output
"Welcome to Shell Scripting
Prints the date
Defining Variables in Shell Scripts
Variables in shell scripts allow you to store and manipulate data during script execution.
Here is a comprehensive guide:
1. Basic Syntax
The syntax for defining a variable is:
variable_name=value
• No spaces are allowed around the = sign.
• Variable names are case-sensitive.
2. Accessing Variables
To access a variable's value, use the $ symbol before the variable name:
echo $variable_name
3. Examples
3 Gmail id : opskillsup@[Link] Contact :7483-537- 551
String Variable #!/bin/bash
greeting="Hello, World!"
echo $greeting
Output: Hello, World!
Numeric Variable
#!/bin/bash
number=42 echo
$number
Output: 42
Command Output as Variable
#!/bin/bash current_date=$(date)
echo "Today's date is: $current_date"
Output: Today's date is: [current date and time]
4. Best Practices
4.1 Use Quotes for Strings
Always wrap string values in quotes, especially if they contain
spaces. my_var="This is a string with spaces" echo $my_var
4.2 Use Curly Braces for Concatenation
Use ${} to avoid ambiguity when concatenating strings.
my_var="World" echo
"Hello, ${my_var}!"
Output: Hello, World!
4.3 Export Variables for Child Processes
Use export to make a variable accessible to child scripts or processes.
export my_var="Exported Value"
4.4 Avoid Overwriting System Variables
4 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Be cautious not to overwrite predefined variables like PATH, USER, or HOME.
5. Special Variable Types
5.1 Readonly Variables
A variable that cannot be modified.
readonly my_var="Cannot be modified" my_var="Try
to change" # This will throw an error
5.2 Unset Variables
Remove a variable from memory.
unset my_var echo $my_var # Will
print nothing
5.3 Environment Variables
Make variables available globally to other scripts and processes.
export MY_VAR="Global Variable"
6. Common Use Cases
Example 1: Basic Script
#!/bin/bash echo "What is
your name?" read name
echo "Hello, $name!"
This script asks for the user’s name and greets them.
Example 2: Check Directory Existence
#!/bin/bash
if [ -d "/tmp" ]; then
echo "The /tmp directory exists." else
echo "The /tmp directory does not exist."
5 Gmail id : opskillsup@[Link] Contact :7483-537- 551
fi
Example 3: Arithmetic Operation
#!/bin/bash num1=5
num2=10 sum=$((num1
+ num2)) echo "The sum
is: $sum"
Output: The sum is: 15
7. Key Points to Remember
• Always use quotes for string values.
• Export variables if needed by child processes.
• Use meaningful names to make your script readable.
• Handle errors gracefully by checking command outcomes (using $?).
Explanation of common special characters and variables in shell scripting
Positional Parameters
1. $0
• Refers to the name of the script or the command used to invoke it.
• Example: If your script is named [Link], $0 will return [Link].
2. $1, $2, $3, ...
• Represent the arguments passed to the script or function.
• $1 is the first argument, $2 is the second, and so on.
Example:
6 Gmail id : opskillsup@[Link] Contact :7483-537- 551
./[Link] arg1 arg2
echo $1 # Output: arg1
echo $2 # Output: arg2
3. $#
• Indicates the number of arguments passed to the script. •
Example: If you run ./[Link] arg1 arg2, $# will return 2.
4. $@
• Represents all the arguments passed to the script as a
separate list.
Example:
./[Link] arg1 arg2
echo $@ # Output: arg1 arg2
5. $*
• Similar to $@ but treats all arguments as a single string
Example
./[Link] arg1 arg2
echo $* # Output: arg1 arg2
Special Variables
1. $$
• The process ID (PID) of the script currently running.
Example
echo $$ # Output: Process ID of the script
7 Gmail id : opskillsup@[Link] Contact :7483-537- 551
2. $?
• The exit status of the last executed command. Example
ls /nonexistent_directory echo $? # Output: 1
(non-zero indicates failure) 0 success
3. $_
• The last argument of the last executed command
• If statement
The if statement in a shell script is used to perform conditional execution of
commands. Here's the syntax and examples:
Basic Syntax:
if [ condition ] then
commands
fi
Alternate Syntax:
if [ condition ]; then commands fi
Examples
1. Simple If Statement
#!/bin/bash
# Check if a file exists
8 Gmail id : opskillsup@[Link] Contact :7483-537- 551
if [ -f "/path/to/file" ]
then
echo "File exists." fi
2. If-Else Statement
If-Elif-Else Statement
9 Gmail id : opskillsup@[Link] Contact :7483-537- 551
3. If-Elif-Else Statement
10 Gmail id : opskillsup@[Link] Contact :7483-537- 551
4. Logical Operators in Conditions
• AND: -a or &&
• OR: -o or ||
5. String Comparison
11 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Common Test Conditions:
Numeric Comparison Operators
12 Gmail id : opskillsup@[Link] Contact :7483-537- 551
String Comparison Operators
Enable Debugging Mode (-x, -v) Shell
provides built-in options to debug scripts:
Debug the whole script: Add set -x at the start of your script and set +x where
debugging should stop.
13 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Shell script to check the file is empty
Explanation
• -f "$file": Checks if the file exists and is a regular file.
• -s "$file": Checks if the file is not empty.
shell script that checks whether a given input is a file, directory, or symbolic link:
14 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Explanation
1. Checks if the path exists:
• -e "$path": Checks if the file, directory, or link exists.
2. Identifies the type:
• -f "$path": Checks if the path is a regular file.
• -d "$path": Checks if the path is a directory.
• -L "$path": Checks if the path is a symbolic link.
3. Handles non-existent paths:
• If the path doesn't exist, it prints a message indicating so.
Cron Job
15 Gmail id : opskillsup@[Link] Contact :7483-537- 551
A cron job is a scheduled task or command that runs automatically at specified
intervals on Unix-like operating systems. It is managed by the cron daemon, which
executes tasks based on the schedule defined in the crontab file.
The Five Fields in a Cron Job
* * * * * /path/to/command_or_script
Fields Explanation
• Minute (0–59): The minute of the hour when the task will run.
• Hour (0–23): The hour of the day when the task will run.
• Day of Month (1–31): The specific day of the month when the task will run.
• Month (1–12): The month when the task will run.
• Day of Week (0–7): The day of the week (Sunday is 0 or 7).
Examples:
1. * * * * * /path/to/[Link] - Run a script every minute
2. 0 17 * * * /path/to/[Link] - Run a script every day at 5 PM
3. 0 6 * * 1 /path/to/[Link] - Run a script every Monday at 6 AM
4. 30 2 * * * /path/to/[Link] - Run a script at 2:30 AM every day
5. 0 0 * * 5 /path/to/[Link] - Run a script every Friday at midnight
6. 0 7 1 * * /path/to/[Link] - Run a script on the 1st of every month at 7 AM
7. 0 * * * 1-5 /path/to/[Link] - Run a script every hour on weekdays (Monday–
Friday)
8. */15 * * * * /path/to/[Link] - Run a script every 15 minutes
9. 0 8-20/2 * * * /path/to/[Link] - 0 8-20/2 * * * /path/to/[Link]
10. 0 3 1 1,7 * /path/to/[Link] - Run a script every 6 months on the 1st of
January and July at 3 AM
11. 59 23 * * * [ "$(date +\%d -d tomorrow)" == "01" ] && /path/to/[Link] -to
run last day of the every month
crontab -e – Edit Crontab crontab
-l - List Existing Cron Jobs crontab
-r - Remove All Cron Jobs Loops
In shell scripts
16 Gmail id : opskillsup@[Link] Contact :7483-537- 551
1. for Loop
The for loop iterates over a list of items or a range.
Examples
• Iterating Over a List:
Output
• Iterating Over a Range:
Output:
17 Gmail id : opskillsup@[Link] Contact :7483-537- 551
2. while Loop
The while loop continues as long as the condition evaluates to true. Syntax
Example
Output
3. until Loop
18 Gmail id : opskillsup@[Link] Contact :7483-537- 551
The until loop continues until the condition becomes true
Example
Output:
4. select Loop
The select loop is used to create simple menus for user input.
Syntax
Example
19 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Output (Example interaction):
5. break Statement
The break statement is used to exit a loop prematurely.
Example
Output
6. continue Statement
The continue statement skips the rest of the loop body for the current iteration and
moves to the next iteration.
Example
20 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Output
7. Infinite Loops
• while Infinite Loop
• for Infinite Loop
8. Nested Loops
Loops can be nested for complex tasks
Example
21 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Output:
Summary of Loop Types
For Loop
A for loop in shell scripting is used to execute a block of code repeatedly for each
item in a list or a range of values. It is one of the most commonly used control
structures for iterating over a set of items.
22 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Syntax
for variable in list
do
commands
done
• variable: A placeholder that takes on each value in the list during iteration.
• list: A set of values or items to iterate through. This can be numbers, strings,
file names, or commands.
• commands: The block of code to be executed for each item in the list.
How It Works
1. The loop starts by assigning the first value of the list to the variable.
2. The commands inside the loop are executed with the variable holding the
current value.
3. After the commands are executed, the loop moves to the next value in the
list.
4. This continues until all values in the list are processed.
Example 1: Batch Renaming Files
Suppose you have a directory containing multiple .txt files, and you want to rename
all of them to have a .bak extension.
23 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Explanation:
• for file in "$directory"/*.txt: Iterates over each .txt file in the specified
directory.
• basename "$file" .txt: Extracts the base name of the file without the .txt
extension.
• mv "$file" "$directory/$base_name.bak": Renames the file by changing its
extension to .bak.
Example 2: Monitoring Disk Usage
This script checks the disk usage of multiple directories and alerts if any directory
exceeds a specified threshold.
24 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Explanation:
• directories=("/home" "/var" "/tmp"): An array of directories to monitor.
• df -h "$dir": Retrieves human-readable disk usage statistics for the
directory.
• awk 'NR==2 {print $5}': Extracts the usage percentage from the output.
• sed 's/%//': Removes the percentage sign for numerical comparison.
• if [ "$usage" -gt "$threshold" ]: Compares the usage with the threshold
and prints a warning if it exceeds.
While loop
A while loop in shell scripting allows you to execute a block of code repeatedly as
long as a specified condition remains true. It's particularly useful for scenarios
where the number of iterations isn't predetermined but depends on dynamic
conditions.
Syntax:
25 Gmail id : opskillsup@[Link] Contact :7483-537- 551
while [ condition ] do
# Commands to execute done
Explanation:
• The condition is evaluated before each iteration.
• If the condition evaluates to true, the commands within the loop are
executed.
• This process repeats until the condition evaluates to false.
Example 1: Monitoring a Service Status
This script continuously checks if a service (e.g., httpd) is running and restarts it if
it's not.
Explanation:
• The while true loop creates an infinite loop that runs indefinitely.
• systemctl is-active --quiet $service checks if the specified service is active.
• If the service is not running, systemctl start $service attempts to start it.
• The script waits for 60 seconds before repeating the check, preventing
constant polling.
Example 2: User Input Validation
26 Gmail id : opskillsup@[Link] Contact :7483-537- 551
This script prompts the user to enter a number between 1 and 10 and continues to
prompt until a valid input is provided.
Explanation:
• The script uses a while loop to validate user input.
• The condition ! [[ "$number" =~ ^[1-9]$|^10$ ]] checks if the input is not a
number between 1 and 10.
• If the input is invalid, the user is prompted again until a valid number is
entered.
Until loop
An until loop in shell scripting repeatedly executes a block of commands until a
specified condition becomes true. It is the opposite of a while loop, which
continues as long as a condition is true. Syntax
until [ condition ]; do
# Commands to execute
\ done
27 Gmail id : opskillsup@[Link] Contact :7483-537- 551
• The loop will continue executing the commands until the condition
evaluates to true.
• Once the condition becomes true, the loop exits.
Example: Counting Down from 10 to 1
How It Works
1. The until loop checks the condition [ $counter -le 0 ]:
• If counter is greater than 0, the loop executes.
• If counter is less than or equal to 0, the loop exits.
2. Inside the loop, it decrements the counter by 1 and prints the current value.
Interview Shell script
Write a script to print the first 10 even numbers.
Explanation:
• The loop starts at 2 and increments by 2 until 20.
28 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Scenario 1: Automate Log Cleanup
Question: Your system generates log files daily, and you need to delete log files older than 7 days
from /var/logs/app/. How would you write a shell script to automate this?
Explanation:
• find $LOG_DIR -type f -mtime +7 → Finds files older than 7 days.
• -exec rm -f {} → Deletes those files.
Scenario 2: Monitor Disk Space and Send Alert
Question: You need to monitor disk space on a Linux server and send an alert email if
usage exceeds 80%. How would you achieve this?
Explanation:
• df -h / → Gets disk usage.
• awk 'NR==2 {print $5}' → Extracts the percentage.
• if [ "$USAGE" -gt "$THRESHOLD" ]; then ... → Checks if it's above 80% and sends an email.
29 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Scenario 3: Backup a Directory Automatically
Question: You need to back up the /home/user/data directory daily to /backup. How would you
write a script for this?
Explanation:
• tar -czf $DEST $SRC → Compresses and saves the backup with the current date.
• echo confirms the backup is complete.
Scenario 5: Check if a Website is Up
Question: How would you write a script to check if [Link] is online and alert if
it's down?
30 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Explanation:
• curl -Is "$URL" | head -n 1 | grep "200" → Checks HTTP response.
• If not 200 OK, sends an email alert.
Detect High CPU Usage and Kill Process
Question: Write a script that checks for processes consuming more than 90% CPU and kills them
automatically.
#!/bin/bash
THRESHOLD=90
ps -eo pid,ppid,cmd,%cpu --sort=-%cpu | awk -v threshold=$THRESHOLD 'NR>1 {if ($4 >
threshold) print $1, $4}' | while read pid cpu; do
echo "Process $pid is consuming $cpu% CPU. Killing..."
kill -9 $pid
done
Explanation:
• ps -eo pid,ppid,cmd,%cpu --sort=-%cpu → Lists all processes sorted by CPU usage.
• awk extracts processes above the threshold.
• kill -9 $pid forcefully terminates high CPU-consuming processes.
31 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Failover Mechanism for Web Servers
Question: You have two web servers (server1 and server2). If server1 is down, traffic
should be switched to server2 automatically. Write a script for this.
Explanation:
• Checks if server1 responds with HTTP 200.
• If down, switches traffic to server2 (you can integrate DNS or Load Balancer updates).
Scenario 3: Monitor Memory Usage and Free Up Space
Question: Write a script to check memory usage, and if free memory is below 10%, clear cache.
32 Gmail id : opskillsup@[Link] Contact :7483-537- 551
Explanation:
• Checks free memory.
• If below 10%, clears caches using sync; echo 3 > /proc/sys/vm/drop_caches.
Auto-Restore a Deleted File
Question: If a critical file (/etc/[Link]) is deleted, it should be restored from a
backup.
Explanation:
• Runs an infinite loop checking if the file exists.
• If deleted, restores it from a backup.
33 Gmail id : opskillsup@[Link] Contact :7483-537- 551