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

Shell Scripting Interview

Unix shell scripting involves writing scripts to automate tasks in Unix-based systems using a command-line interpreter. A shell script contains a series of commands that can perform various functions such as managing system tasks, automating backups, and scheduling jobs with cron. Key components of shell scripting include variables, conditionals, loops, and file operations, which can be utilized to create efficient automation solutions.

Uploaded by

foheke6586
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views56 pages

Shell Scripting Interview

Unix shell scripting involves writing scripts to automate tasks in Unix-based systems using a command-line interpreter. A shell script contains a series of commands that can perform various functions such as managing system tasks, automating backups, and scheduling jobs with cron. Key components of shell scripting include variables, conditionals, loops, and file operations, which can be utilized to create efficient automation solutions.

Uploaded by

foheke6586
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

What is Unix shell scripting??

ChatGPT said:

Unix shell scripting is the process of writing scripts using a shell — a command-line
interpreter in Unix-based systems like Linux or macOS — to automate tasks.

What is a Shell?

A shell is a program that takes commands from the user and passes them to the operating
system to execute. Common shells include:

 Bash (Bourne Again SHell) – most widely used


 Sh (Bourne Shell)
 Zsh (Z Shell)
 Ksh (Korn Shell)

What is Shell Scripting?

A shell script is a file containing a series of shell commands that the shell can execute as a
program. It typically has a .sh extension.

Why Use Shell Scripting?

 Automate repetitive tasks (e.g., backups, deployments)


 Manage system tasks (e.g., file operations, process control)
 Chain multiple Unix commands together
 Schedule tasks via cron jobs

Basic Shell Script Example


sh
CopyEdit
#!/bin/bash
echo "Hello, $USER!"
echo "Today is $(date)"

 #!/bin/bash is called a shebang and tells the system to use the Bash shell to run the
script.
 echo prints output to the terminal.
 $(date) runs the date command and inserts its output.

Let me know if you'd like help writing a shell script for a specific use case!

4o

You said:

I am beginner can you share all the syntax and explain everything about them broadly
ChatGPT said:
Updated saved memory

Absolutely! Here's a beginner-friendly breakdown of Unix Shell Scripting, including syntax


and concepts with broad explanations.

1. What is a Shell Script?


A shell script is a text file containing a sequence of commands for the Unix shell to execute.

Example filename: myscript.sh

2. Shebang (#!)
The first line of a shell script is usually the shebang line.

sh
CopyEdit
#!/bin/bash

 Tells the system which interpreter to use.


 For Bash shell, use /bin/bash.

3. Comments
sh
CopyEdit
# This is a comment

 Use # to add comments (ignored by the shell).


 Good for explaining what each part of the script does.

4. Variables
Declare and use variables:
sh
CopyEdit
name="Alice"
echo "Hello, $name"

 No spaces around =.
 Access using $variable_name.

Read user input:


sh
CopyEdit
read -p "Enter your name: " name
echo "Hello, $name"

5. Data Types
Shell treats all variables as strings by default, even numbers.

6. Conditionals (if-else)
Basic if:
sh
CopyEdit
if [ $age -gt 18 ]
then
echo "Adult"
fi

if-else:
sh
CopyEdit
if [ $age -gt 18 ]; then
echo "Adult"
else
echo "Minor"
fi

if-elif-else:
sh
CopyEdit
if [ $age -lt 13 ]; then
echo "Child"
elif [ $age -lt 20 ]; then
echo "Teenager"
else
echo "Adult"
fi

7. Comparison Operators
Numbers:

Operator Meaning
-eq Equal
-ne Not equal
-gt Greater than
-lt Less than
-ge Greater or equal
-le Less or equal

Strings:

Operator Meaning
= Equal
!= Not equal
-z Is empty
-n Is not empty

8. Loops
While loop:
sh
CopyEdit
i=1
while [ $i -le 5 ]
do
echo "Number $i"
i=$((i+1))
done

For loop:
sh
CopyEdit
for i in 1 2 3 4 5
do
echo "Number $i"
done

Until loop:
sh
CopyEdit
i=1
until [ $i -gt 5 ]
do
echo "Number $i"
i=$((i+1))
done
9. Functions
sh
CopyEdit
greet() {
echo "Hello $1"
}

greet "Alice"

 $1 is the first argument to the function.

10. File Testing


sh
CopyEdit
if [ -f file.txt ]; then
echo "File exists"
fi

Common file test options:

Option Checks if...


-f File exists and is a regular file
-d Directory exists
-e File exists (any type)
-r File is readable
-w File is writable
-x File is executable

11. Arithmetic Operations


Use expr or $(( )):

sh
CopyEdit
a=5
b=3
sum=$((a + b))
echo "Sum is $sum"

12. Special Variables


Variable Meaning
$0 Script name
$1, $2... Arguments passed to the script
$# Number of arguments
$@ All arguments
$$ Script PID
$? Exit status of last command

13. Exit Status


sh
CopyEdit
command
echo $?

 0means success
 Non-zero means error

14. Case Statement


sh
CopyEdit
echo "Enter a choice:"
read choice
case $choice in
1) echo "Option 1";;
2) echo "Option 2";;
*) echo "Invalid choice";;
esac

15. Input/Output Redirection


sh
CopyEdit
command > file.txt # redirect output to file
command >> file.txt # append output
command < input.txt # read input from file

Would you like me to provide a PDF version of this guide or give practice exercises based
on these topics?

4o

You said:
How I backup MySQL db by adding some cron job ??? Also gives some real life example
and do this with scripting then explain all of them
ChatGPT said:

Great question! Automating MySQL database backups with cron jobs and shell scripting is
a real-world task that system admins and developers do often. Let's go step-by-step.

Goal
1. Create a shell script that backs up a MySQL database.
2. Schedule it using cron to run at a specific time (e.g., daily at 2 AM).
3. Explain everything with real-life examples.

Step 1: Create the Shell Script


Script: backup_mysql.sh
sh
CopyEdit
#!/bin/bash

# === CONFIG ===


DB_NAME="your_database"
DB_USER="your_username"
DB_PASS="your_password"
BACKUP_DIR="/home/your_user/db_backups"
DATE=$(date +%F_%H-%M-%S)
FILE_NAME="$DB_NAME-$DATE.sql"

# === CREATE BACKUP DIRECTORY IF IT DOESN'T EXIST ===


mkdir -p "$BACKUP_DIR"

# === RUN BACKUP ===


mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$BACKUP_DIR/$FILE_NAME"

# === DELETE OLD BACKUPS (older than 7 days) ===


find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm {} \;

# === LOG OUTPUT ===


echo "Backup completed for $DB_NAME at $DATE" >> "$BACKUP_DIR/backup.log"

Save this file as backup_mysql.sh and make it executable:

bash
CopyEdit
chmod +x backup_mysql.sh
Step 2: Schedule It Using Cron
Open the crontab:
bash
CopyEdit
crontab -e

Add this line to run the script daily at 2 AM:


bash
CopyEdit
0 2 * * * /home/your_user/backup_mysql.sh

This means:

sql
CopyEdit
Minute Hour Day Month Weekday Command
0 2 * * * Run daily at 2 AM

Explanation of the Script


Line Meaning
#!/bin/bash Use Bash shell for this script
DB_NAME="your_database" Name of your MySQL DB
DATE=$(date +%F_%H-%M-%S) Get timestamp like 2025-04-16_02-00-00
mkdir -p "$BACKUP_DIR" Create the backup folder if it doesn't exist
mysqldump ... MySQL backup command to export your DB
find ... -mtime +7 Remove backup files older than 7 days
>> "$BACKUP_DIR/backup.log" Log each backup

Real-Life Use Case


Example: You run an e-commerce site, and you want to:

 Backup your shopdb every night at 2 AM


 Store backups in /var/backups/mysql
 Keep backups for 7 days only

Your modified script would look like:

sh
CopyEdit
DB_NAME="shopdb"
DB_USER="root"
DB_PASS="mypassword"
BACKUP_DIR="/var/backups/mysql"
Cron job:

bash
CopyEdit
0 2 * * * /var/backups/mysql/backup_mysql.sh

Optional Enhancements
 Compress backups with gzip:

sh
CopyEdit
mysqldump ... | gzip > "$BACKUP_DIR/$FILE_NAME.gz"

 Email on failure/success
 Upload to cloud (AWS S3, Google Drive)

Would you like me to:

 Generate a sample script based on your actual database?


 Show how to restore from a backup file?
 Provide this as a downloadable .sh or .pdf?

You said:

find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm {} \; Explain everything


about this command
ChatGPT said:

Absolutely! Let’s break down this powerful command piece by piece:

sh
CopyEdit
find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm {} \;

This command is used to find and delete .sql backup files older than 7 days in your
backup directory.

Component-by-Component Breakdown

Part Explanation
find Unix command used to search for files and directories.
"$BACKUP_DIR"
The directory where the search begins (e.g., /home/user/db_backups).
This variable was defined earlier in the script.
-type f Limits the search to files only (not directories).
Part Explanation
-name "*.sql" Finds files with names ending in .sql (i.e., MySQL backup files).
-mtime +7 Filters files modified more than 7 days ago.
-exec Tells find to execute a command on each file it finds.
rm {}
The command to run — in this case, rm to delete the file. {} is a placeholder
for the current file name.
\;
Escapes the semicolon, which is required to end the -exec clause. The
backslash prevents the shell from interpreting it early.

How It Works Together

1. Searches the $BACKUP_DIR for files.


2. Filters to only .sql files older than 7 days.
3. Deletes each of them using rm.

Real-Life Analogy

Imagine you're cleaning up your Downloads folder and saying:

"Find every PDF I downloaded over a week ago, and trash it."

This command is doing that — but for .sql files — automatically, on a schedule.

Test Before Deleting

Always test first to see what would be deleted:

sh
CopyEdit
find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7

Once you confirm it's safe, use the -exec rm version.

Would you like a visual diagram showing this flow or a script version that includes email
notifications for deleted files?

You said:

mtime +7 Like this how I specify hours minutes or any time frame is present
ChatGPT said:
Great follow-up! The find command has flexible options for filtering by time, but here's the
important part:

-mtime, -ctime, and -atime deal only with days.


If you want to filter by hours, minutes, or more precise time, you use -mmin or other tools
like stat, date, or find with custom logic.

Time-Based Filters in find


1. Days-Based

Option Description
-mtime +7 Modified more than 7 days ago
-mtime -7 Modified within the last 7 days
-mtime 7 Modified exactly 7 days ago

2. Minutes-Based (-mmin)

Example Meaning
-mmin +60 Modified more than 60 minutes ago
-mmin -30 Modified within the last 30 minutes
-mmin 10 Modified exactly 10 minutes ago (not common use)

Example:

sh
CopyEdit
find . -type f -name "*.log" -mmin +120

Finds log files modified more than 2 hours ago

3. Last Accessed (-atime, -amin)

Option Description
-atime +1 Last accessed more than 1 day ago
-amin -15 Last accessed within the last 15 minutes

4. Changed (-ctime, -cmin)

Option Description
-ctime +2Last status change more than 2 days ago
-cmin -5 Last status change within last 5 minutes
"Status change" includes permission changes, ownership, etc.

Use Case Example


Delete all .tmp files not touched in the last 3 hours:

sh
CopyEdit
find /tmp -type f -name "*.tmp" -mmin +180 -exec rm {} \;

Would you like a cheat sheet of all find time options or a script that deletes files based on
custom hour ranges?

You said:

Give me some real life example where I am using scripting and give Solution and explain
everything
ChatGPT said:

Perfect! Let’s look at 3 real-life scenarios where shell scripting can make your life easier —
each with a problem, a script-based solution, and a full explanation.

1. Real-Life Scenario: Daily MySQL Backup with Cleanup


Problem:

You manage a database and need to:

 Backup the MySQL DB every night


 Save it with a timestamp
 Keep backups only for the last 7 days

Script:
bash
CopyEdit
#!/bin/bash

DB_NAME="store"
DB_USER="root"
DB_PASS="root123"
BACKUP_DIR="/home/ubuntu/db_backups"
DATE=$(date +%F_%H-%M-%S)
FILE="$DB_NAME-$DATE.sql"

mkdir -p "$BACKUP_DIR"
mysqldump -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$BACKUP_DIR/$FILE"

# Delete backups older than 7 days


find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm {} \;

echo "Backup completed: $FILE" >> "$BACKUP_DIR/backup.log"

Explanation:

 Automates DB backup with mysqldump


 Uses date for timestamping files
 Deletes old .sql files using find
 Logs success in a backup.log file

Run it daily with cron:

bash
CopyEdit
0 2 * * * /home/ubuntu/backup_mysql.sh

2. Real-Life Scenario: Check Server Disk Space and Send


Warning
Problem:

Your server fills up with log files and stops working. You need a script that:

 Checks disk usage


 Sends a warning if usage > 80%

Script:
bash
CopyEdit
#!/bin/bash

USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')

if [ "$USAGE" -gt 80 ]; then


echo "WARNING: Disk usage is ${USAGE}%!" | mail -s "Disk Space Alert"
[email protected]
fi

Explanation:

 df / gets disk usage of root


 awk & sed clean the percentage number
 If usage > 80%, sends email using mail command

Run it every hour with cron:


bash
CopyEdit
0 * * * * /home/ubuntu/check_disk.sh

3. Real-Life Scenario: Rename Files in a Folder with


Timestamps
Problem:

You receive files in /incoming/ folder with unclear names like data.csv. You want to:

 Rename each file with a timestamp (e.g., data-2025-04-16_14-00.csv)


 Move them to /processed/

Script:
bash
CopyEdit
#!/bin/bash

SRC_DIR="/home/ubuntu/incoming"
DEST_DIR="/home/ubuntu/processed"
TIMESTAMP=$(date +%F_%H-%M)

for FILE in "$SRC_DIR"/*; do


BASENAME=$(basename "$FILE")
EXT="${BASENAME##*.}"
NAME="${BASENAME%.*}"
mv "$FILE" "$DEST_DIR/${NAME}-${TIMESTAMP}.${EXT}"
done

Explanation:

 Loops through all files in incoming folder


 Extracts filename and extension
 Renames and moves them with timestamp

Want More?
Would you like:

 A PDF cheat sheet of real-world scripts?


 To combine any of these into one powerful script?
 An exercise project to practice these skills?

Let me know!

You said:
echo "WARNING: Disk usage is ${USAGE}%!" | mail -s "Disk Space Alert"
[email protected] Without mail send credentials how the mail send??? ----_-------------------
Give some more real life example with solution and explaination
ChatGPT said:

Great catch! You're absolutely right to ask — how does mail send email without
credentials?

About the mail Command (and Email Without Credentials)


The mail (or mailx) command:

 Uses the local mail transfer agent (MTA) installed on the system — like Postfix,
Sendmail, or ssmtp
 These tools can send mail:
o Locally (to users on the same server)
o Or externally, if configured with SMTP (like Gmail, Outlook)

So:

If your system isn't set up with an MTA or SMTP relay, the mail command will fail silently
or just not deliver externally.

To send external email (e.g., Gmail), you must configure a tool like ssmtp, msmtp, or Postfix
with credentials in /etc/ssmtp/ssmtp.conf or similar.

Now — More Real-Life Scripting Examples

4. Auto-Cleanup: Delete Old Log Files

Problem: Your logs directory is growing large. You only want to keep the last 3 days of
logs.

Script:

bash
CopyEdit
#!/bin/bash
LOG_DIR="/var/log/myapp"
find "$LOG_DIR" -type f -name "*.log" -mtime +3 -exec rm -f {} \;

Explanation:
 Deletes .log files older than 3 days
 Can run daily via cron:

bash
CopyEdit
0 1 * * * /home/ubuntu/clean_logs.sh

5. Real-Time Service Health Checker

Problem: You want to monitor a web service and restart it if it goes down.

Script:

bash
CopyEdit
#!/bin/bash
SERVICE_URL="http://localhost:8080"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$SERVICE_URL")

if [ "$STATUS" -ne 200 ]; then


echo "[$(date)] Service is down! Restarting..." >>
/var/log/service_monitor.log
systemctl restart myapp.service
fi

Explanation:

 Uses curl to check if the HTTP status code is 200 OK


 Logs the downtime and restarts the service

Run every 5 mins with cron:

bash
CopyEdit
*/5 * * * * /home/ubuntu/monitor_service.sh

6. Send Birthday Reminder from File

Problem: You want to send reminders for upcoming birthdays stored in a file.

Data file: birthdays.txt

CopyEdit
John,1995-04-17
Alice,2000-05-01

Script:

bash
CopyEdit
#!/bin/bash
TODAY=$(date +%m-%d)
while IFS=',' read -r name bday; do
BIRTHDAY=$(date -d "$bday" +%m-%d)
if [ "$BIRTHDAY" == "$TODAY" ]; then
echo "Reminder: It's $name's birthday today!"
fi
done < birthdays.txt

Explanation:

 Reads each line from birthdays.txt


 Checks if today's date matches birthday (ignoring year)

7. Auto Archive Reports

Problem: You generate daily reports and want to zip them after 3 days.

Script:

bash
CopyEdit
#!/bin/bash
REPORT_DIR="/home/ubuntu/reports"

find "$REPORT_DIR" -type f -name "*.txt" -mtime +3 -exec gzip {} \;

Explanation:

 Compresses all .txt files older than 3 days


 Reduces storage usage

Want me to generate:

 A GitHub-ready collection of these scripts?


 A dashboard to manage these with logs?
 Or turn these into .sh files and email you in a zip?

Let me know how you want to use them.

You said:

How I define list in scripting both in program and also user defined
ChatGPT said:

Great question! In Unix shell scripting (Bash), lists are generally handled using arrays.
Let’s break it down into:
1. Program-defined (static) lists
2. User-defined (dynamic) lists - via input
3. Common operations on lists
4. Real-world example using lists

1. Program-Defined (Static) List


You define an array like this:

bash
CopyEdit
fruits=("apple" "banana" "cherry")

 fruits[0] → apple
 fruits[1] → banana
 fruits[2] → cherry

Loop through it:

bash
CopyEdit
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done

2. User-Defined List (Dynamic via Input)


Ask user to enter items into a list:
bash
CopyEdit
echo "Enter your favorite 3 fruits:"
read -p "Fruit 1: " f1
read -p "Fruit 2: " f2
read -p "Fruit 3: " f3

fruits=("$f1" "$f2" "$f3")

echo "You entered: ${fruits[@]}"

You can now loop or process them just like any static array.

3. Common List (Array) Operations


Operation Example
All elements ${fruits[@]}
Operation Example
Length of array ${#fruits[@]}
Specific index ${fruits[1]}
Add new item fruits+=("orange")
Remove item (e.g., index 1) unset fruits[1]
Loop with index for i in "${!fruits[@]}"

4. Real-Life Example: List of Filenames


Problem: Rename a list of files with a prefix.
bash
CopyEdit
files=("report1.txt" "report2.txt" "data.csv")

for file in "${files[@]}"; do


mv "$file" "backup_$file"
done

This will rename:

 report1.txt → backup_report1.txt
 data.csv → backup_data.csv

Bonus: User Enters a Comma-Separated List


bash
CopyEdit
read -p "Enter a comma-separated list of fruits: " input
IFS=',' read -ra fruits <<< "$input"

for fruit in "${fruits[@]}"; do


echo "$fruit"
done

Example Input: apple,banana,grape


Output:

nginx
CopyEdit
apple
banana
grape

Would you like a hands-on mini project using lists, like a to-do manager or batch file
processor?

You said:
Yes
ChatGPT said:

Great! Let’s create a simple To-Do Manager script that uses lists (arrays) to:

 Add tasks
 List tasks
 Remove tasks
 Mark tasks as done

This will help you practice manipulating arrays and using user input dynamically.

To-Do Manager Script:


bash
CopyEdit
#!/bin/bash

# Initialize the To-Do list array


todos=()

# Function to display the menu


display_menu() {
echo "==== To-Do Manager ===="
echo "1. Add Task"
echo "2. List Tasks"
echo "3. Remove Task"
echo "4. Mark Task as Done"
echo "5. Exit"
}

# Function to add a new task


add_task() {
read -p "Enter the task description: " task
todos+=("$task")
echo "Task added!"
}

# Function to list all tasks


list_tasks() {
if [ ${#todos[@]} -eq 0 ]; then
echo "No tasks to display."
else
echo "==== Your Tasks ===="
for i in "${!todos[@]}"; do
echo "$((i+1)). ${todos[$i]}"
done
fi
}

# Function to remove a task


remove_task() {
list_tasks
read -p "Enter the task number to remove: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
unset todos[$((task_number - 1))]
todos=("${todos[@]}") # Re-index the array
echo "Task removed!"
else
echo "Invalid task number!"
fi
}

# Function to mark a task as done


mark_done() {
list_tasks
read -p "Enter the task number to mark as done: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
todos[$((task_number - 1))]="${todos[$((task_number - 1))]} (Done)"
echo "Task marked as done!"
else
echo "Invalid task number!"
fi
}

# Main loop to display the menu and get user input


while true; do
display_menu
read -p "Choose an option (1-5): " choice

case $choice in
1) add_task ;;
2) list_tasks ;;
3) remove_task ;;
4) mark_done ;;
5) echo "Exiting..."; break ;;
*) echo "Invalid option, try again." ;;
esac
done

Explanation of the Script

1. Arrays and User Input:

 The todos array holds the list of tasks.


 We add tasks dynamically using the += operator and get input from the user with
read.

2. Functions:

 add_task: Prompts the user to enter a task and appends it to the todos array.
 list_tasks: Loops through the todos array to display all tasks with their indices.
 remove_task: Removes a task by its index, and the array is re-indexed.
 mark_done: Marks a task as done by appending "(Done)" to its description.

3. Main Loop:

 The script presents a menu to the user to either add, list, remove, mark tasks, or exit.
 The menu continues to run until the user chooses to exit.
How to Run the Script:

1. Copy the script into a file called todo_manager.sh.


2. Make the script executable:

bash
CopyEdit
chmod +x todo_manager.sh

3. Run the script:

bash
CopyEdit
./todo_manager.sh

Example Interaction
bash
CopyEdit
==== To-Do Manager ====
1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Exit
Choose an option (1-5): 1
Enter the task description: Buy groceries
Task added!

==== To-Do Manager ====


1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Exit
Choose an option (1-5): 2
==== Your Tasks ====
1. Buy groceries

==== To-Do Manager ====


1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Exit
Choose an option (1-5): 4
Enter the task number to mark as done: 1
Task marked as done!

==== To-Do Manager ====


1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Exit
Choose an option (1-5): 2
==== Your Tasks ====
1. Buy groceries (Done)

Next Steps:

 Enhance the script: Add functionality to save the tasks to a file so they persist after a
restart.
 Use grep for searching tasks: Add a search feature to look for specific tasks.
 Add due dates or priorities: Extend the script to handle tasks with deadlines or
priorities.

Would you like to enhance this further with those features? Or perhaps add another
functionality like reminders?

You said:

Yes
ChatGPT said:

Awesome! Let’s enhance the To-Do Manager script with the following features:

1. Save and load tasks from a file: This will make tasks persistent across script runs.
2. Search for tasks by keyword: You can search tasks easily.
3. Add due dates: Tasks can now have due dates for better tracking.
4. Priorities: You can assign priorities to tasks (e.g., High, Medium, Low).

Enhanced To-Do Manager Script with Additional Features:


bash
CopyEdit
#!/bin/bash

# Initialize the To-Do list file


TODO_FILE="/home/ubuntu/todo_list.txt"

# Function to display the menu


display_menu() {
echo "==== To-Do Manager ===="
echo "1. Add Task"
echo "2. List Tasks"
echo "3. Remove Task"
echo "4. Mark Task as Done"
echo "5. Search Task"
echo "6. Exit"
}

# Function to load tasks from the file


load_tasks() {
if [ -f "$TODO_FILE" ]; then
mapfile -t todos < "$TODO_FILE"
else
todos=()
fi
}

# Function to save tasks to the file


save_tasks() {
for task in "${todos[@]}"; do
echo "$task" >> "$TODO_FILE"
done
}

# Function to add a new task


add_task() {
read -p "Enter the task description: " task_desc
read -p "Enter the due date (yyyy-mm-dd): " due_date
read -p "Enter the priority (High, Medium, Low): " priority

task="Description: $task_desc | Due Date: $due_date | Priority:


$priority"
todos+=("$task")
save_tasks
echo "Task added!"
}

# Function to list all tasks


list_tasks() {
if [ ${#todos[@]} -eq 0 ]; then
echo "No tasks to display."
else
echo "==== Your Tasks ===="
for i in "${!todos[@]}"; do
echo "$((i+1)). ${todos[$i]}"
done
fi
}

# Function to remove a task


remove_task() {
list_tasks
read -p "Enter the task number to remove: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
unset todos[$((task_number - 1))]
todos=("${todos[@]}") # Re-index the array
save_tasks
echo "Task removed!"
else
echo "Invalid task number!"
fi
}

# Function to mark a task as done


mark_done() {
list_tasks
read -p "Enter the task number to mark as done: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
todos[$((task_number - 1))]="${todos[$((task_number - 1))]} (Done)"
save_tasks
echo "Task marked as done!"
else
echo "Invalid task number!"
fi
}

# Function to search tasks by keyword


search_task() {
read -p "Enter the keyword to search for: " keyword
echo "==== Search Results ===="
for task in "${todos[@]}"; do
if [[ "$task" == *"$keyword"* ]]; then
echo "$task"
fi
done
}

# Main loop to display the menu and get user input


load_tasks

while true; do
display_menu
read -p "Choose an option (1-6): " choice

case $choice in
1) add_task ;;
2) list_tasks ;;
3) remove_task ;;
4) mark_done ;;
5) search_task ;;
6) echo "Exiting..."; break ;;
*) echo "Invalid option, try again." ;;
esac
done

Enhancements Explained:

1. Saving and Loading Tasks:


o load_tasks: Loads tasks from a file (todo_list.txt) at the start of the
script. If the file doesn’t exist, it initializes an empty array.
o save_tasks: Saves the current list of tasks to the file each time a change is
made (add, remove, mark done).
2. Search Task by Keyword:
o search_task: Prompts the user for a keyword and searches for it in the tasks.
It shows only the tasks that match the keyword.
3. Due Dates and Priorities:
o When adding a task, the user is prompted to enter a due date and a priority
(e.g., High, Medium, Low).
o The tasks are saved in the format: Description | Due Date | Priority.
4. File Persistence:
o Now, tasks remain persistent between script runs because they are saved in
todo_list.txt.

How to Use the Enhanced Script:


1. Make the script executable:

bash
CopyEdit
chmod +x todo_manager.sh

2. Run the script:

bash
CopyEdit
./todo_manager.sh

Example Interaction
bash
CopyEdit
==== To-Do Manager ====
1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Search Task
6. Exit
Choose an option (1-6): 1
Enter the task description: Complete project report
Enter the due date (yyyy-mm-dd): 2025-04-20
Enter the priority (High, Medium, Low): High
Task added!

==== To-Do Manager ====


1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Search Task
6. Exit
Choose an option (1-6): 2
==== Your Tasks ====
1. Description: Complete project report | Due Date: 2025-04-20 | Priority:
High

==== To-Do Manager ====


1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Search Task
6. Exit
Choose an option (1-6): 5
Enter the keyword to search for: report
==== Search Results ====
Description: Complete project report | Due Date: 2025-04-20 | Priority:
High

Next Steps:
 Enhance search: Search tasks by due date or priority.
 Task sorting: Sort tasks by due date or priority.
 Add notifications: You could add email or SMS notifications for due tasks.

Would you like to go into any of these further or add other specific features?

You said:

Yes
ChatGPT said:

Awesome! Let's take the To-Do Manager script a step further by adding the following
features:

1. Sort Tasks by Due Date and Priority: Sort the tasks based on due date and priority
(e.g., High, Medium, Low).
2. Task Notification: Send an email reminder for tasks that are due today or within the
next day.

Enhanced To-Do Manager with Sorting and Email Notifications:

New Features to Add:

1. Sort Tasks by Due Date and Priority.


2. Email Notification for tasks that are due today or within the next day.

The Updated Script:

bash
CopyEdit
#!/bin/bash

# Initialize the To-Do list file


TODO_FILE="/home/ubuntu/todo_list.txt"

# Function to display the menu


display_menu() {
echo "==== To-Do Manager ===="
echo "1. Add Task"
echo "2. List Tasks"
echo "3. Remove Task"
echo "4. Mark Task as Done"
echo "5. Search Task"
echo "6. Sort Tasks"
echo "7. Exit"
}

# Function to load tasks from the file


load_tasks() {
if [ -f "$TODO_FILE" ]; then
mapfile -t todos < "$TODO_FILE"
else
todos=()
fi
}

# Function to save tasks to the file


save_tasks() {
> "$TODO_FILE"
for task in "${todos[@]}"; do
echo "$task" >> "$TODO_FILE"
done
}

# Function to add a new task


add_task() {
read -p "Enter the task description: " task_desc
read -p "Enter the due date (yyyy-mm-dd): " due_date
read -p "Enter the priority (High, Medium, Low): " priority

task="Description: $task_desc | Due Date: $due_date | Priority:


$priority"
todos+=("$task")
save_tasks
echo "Task added!"
}

# Function to list all tasks


list_tasks() {
if [ ${#todos[@]} -eq 0 ]; then
echo "No tasks to display."
else
echo "==== Your Tasks ===="
for i in "${!todos[@]}"; do
echo "$((i+1)). ${todos[$i]}"
done
fi
}

# Function to remove a task


remove_task() {
list_tasks
read -p "Enter the task number to remove: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
unset todos[$((task_number - 1))]
todos=("${todos[@]}") # Re-index the array
save_tasks
echo "Task removed!"
else
echo "Invalid task number!"
fi
}

# Function to mark a task as done


mark_done() {
list_tasks
read -p "Enter the task number to mark as done: " task_number
if [[ "$task_number" -ge 1 && "$task_number" -le ${#todos[@]} ]]; then
todos[$((task_number - 1))]="${todos[$((task_number - 1))]} (Done)"
save_tasks
echo "Task marked as done!"
else
echo "Invalid task number!"
fi
}

# Function to search tasks by keyword


search_task() {
read -p "Enter the keyword to search for: " keyword
echo "==== Search Results ===="
for task in "${todos[@]}"; do
if [[ "$task" == *"$keyword"* ]]; then
echo "$task"
fi
done
}

# Function to sort tasks by due date and priority


sort_tasks() {
echo "==== Sorting Tasks ===="
sorted_tasks=$(for task in "${todos[@]}"; do
echo "$task"
done | sort -t "|" -k 2,2 -k 3,3)

echo "$sorted_tasks"
}

# Function to send email notification for tasks due today or in the next
day
send_email_notifications() {
TODAY=$(date +%Y-%m-%d)
TOMORROW=$(date -d "+1 day" +%Y-%m-%d)
EMAIL="[email protected]"
SUBJECT="Task Reminders"

email_content="==== Task Reminder ====\n"

for task in "${todos[@]}"; do


due_date=$(echo "$task" | awk -F '|' '{print $2}' | sed 's/ Due
Date: //')
if [[ "$due_date" == "$TODAY" || "$due_date" == "$TOMORROW" ]];
then
email_content+="\n$task"
fi
done

echo -e "$email_content" | mail -s "$SUBJECT" "$EMAIL"


echo "Notification email sent!"
}

# Main loop to display the menu and get user input


load_tasks

while true; do
display_menu
read -p "Choose an option (1-7): " choice

case $choice in
1) add_task ;;
2) list_tasks ;;
3) remove_task ;;
4) mark_done ;;
5) search_task ;;
6) sort_tasks ;;
7) send_email_notifications; echo "Exiting..."; break ;;
*) echo "Invalid option, try again." ;;
esac
done

New Features Explanation:

1. Sort Tasks by Due Date and Priority:


o The sort_tasks function sorts the tasks first by due date (second field) and
then by priority (third field). This helps you organize tasks in the right order.
o The script uses sort with the delimiter | to sort tasks based on the Due Date
and Priority.
2. Email Notifications:
o send_email_notifications: This function sends a notification email for
tasks that are due today or within the next day.
o It uses the mail command to send the email. The email includes all tasks due
today or tomorrow, and the content is formatted to show the task description,
due date, and priority.
o Important: Make sure your server has an MTA (Mail Transfer Agent)
configured (e.g., Postfix, Sendmail, or msmtp) to send the email successfully.

How to Test the Email Notifications:

1. Set up an SMTP server or use a service like msmtp or ssmtp to send emails.
2. Make sure the mail command works on your system by sending a test email:

bash
CopyEdit
echo "Test email body" | mail -s "Test Subject" [email protected]

3. Once the email system is working, you can use the send_email_notifications
function to send notifications.

Example of Sorting Tasks:


bash
CopyEdit
==== To-Do Manager ====
1. Add Task
2. List Tasks
3. Remove Task
4. Mark Task as Done
5. Search Task
6. Sort Tasks
7. Exit
Choose an option (1-7): 6
==== Sorting Tasks ====
1. Description: Complete project report | Due Date: 2025-04-20 | Priority:
High
2. Description: Buy groceries | Due Date: 2025-04-15 | Priority: Medium
3. Description: Call client | Due Date: 2025-04-15 | Priority: Low

Next Steps:

 Enhance sorting: Allow sorting by both due date and priority.


 Enhance email notifications: Send emails at regular intervals (e.g., once a day)
instead of manual triggering.
 Add recurring tasks: Automatically add tasks that repeat (e.g., daily, weekly).

Let me know if you'd like to continue building this out!

You said:

In ubuntu nginx configuration a folder present var/www/html/admin-api where some publish


files and folder present, for publishing website I need to delete all file and folder from admin-
api except appsettings.json and upload folder and it's content under then unzip a zip file of
new publish files and move them to admin-api, write a script to automate this task
ChatGPT said:

Here's a Bash script that automates the process of:

1. Deleting everything from /var/www/html/admin-api except:


o appsettings.json
o upload/ folder (and
all its content)
2. Unzipping a specified ZIP file of new published files
3. Moving the contents of the ZIP file to /var/www/html/admin-api

Script: deploy_admin_api.sh
bash
CopyEdit
#!/bin/bash

# Set variables
TARGET_DIR="/var/www/html/admin-api"
BACKUP_DIR="/var/www/html/backup-admin-api-$(date +%Y%m%d%H%M%S)"
ZIP_FILE="/path/to/your/publish.zip" # <-- Replace this path
TMP_DIR="/tmp/deploy_temp"

# Step 1: Backup existing files (optional but safe)


echo "Backing up current admin-api to $BACKUP_DIR..."
mkdir -p "$BACKUP_DIR"
cp -r "$TARGET_DIR"/* "$BACKUP_DIR" 2>/dev/null

# Step 2: Delete everything except appsettings.json and upload folder


echo "Cleaning $TARGET_DIR..."
find "$TARGET_DIR" -mindepth 1 ! -name 'appsettings.json' ! -name
'upload' ! -path "$TARGET_DIR/upload/*" -exec rm -rf {} +

# Step 3: Unzip the new publish ZIP to a temporary folder


echo "Extracting $ZIP_FILE to temporary folder..."
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"
unzip -q "$ZIP_FILE" -d "$TMP_DIR"

# Step 4: Move contents of extracted folder to target directory


echo "Deploying new files to $TARGET_DIR..."
cp -r "$TMP_DIR"/* "$TARGET_DIR/"

# Step 5: Clean up
rm -rf "$TMP_DIR"

echo "Deployment complete!"

How to Use:

1. Save the script as deploy_admin_api.sh.


2. Make it executable:

bash
CopyEdit
chmod +x deploy_admin_api.sh

3. Edit the script and set the correct path to your zip file.
4. Run it with sudo (if needed):

bash
CopyEdit
sudo ./deploy_admin_api.sh

Script Explanation:

 find ... -exec rm -rf {}: Deletes all items except appsettings.json and
upload/.
 unzip -q: Quietly extracts the ZIP.
 cp -r: Moves new published files to the admin-api folder.
 Backups are stored in a timestamped folder before deletion.

Let me know if you want to make this script reusable with arguments (like ZIP path or target
directory)!

You said:

Explain the different flag used in common command


ChatGPT said:
Sure! Here's a breakdown of common Linux commands and their frequently used flags
(options) with explanations:

1. ls – List Directory Contents


bash
CopyEdit
ls -l -a -h
Flag Description
-l Long listing format (permissions, owner, size, etc.)
-a Shows all files, including hidden ones (.files)
-h Human-readable file sizes (e.g., KB, MB) – works with -l

2. cp – Copy Files or Directories


bash
CopyEdit
cp -r -v -u
Flag Description
-r Recursively copy directories
-v Verbose: show what is being copied
-u Copy only if source file is newer than the destination

3. mv – Move/Rename Files
bash
CopyEdit
mv -v -u
Flag Description
-v Verbose: show what is being moved
-u Update: move only when source is newer

4. rm – Remove Files or Directories


bash
CopyEdit
rm -r -f -v
Flag Description
-r Recursively delete directories
-f Force delete without prompt
-v Verbose: show what's being deleted

5. find – Search for Files


bash
CopyEdit
find . -name "*.sh" -type f -mtime +7 -exec rm {} \;
Flag Description
. Start searching in current directory
-name Search by filename pattern (*.sh = all .sh files)
-type f Look only for files (d = directories)
-mtime +7 Modified more than 7 days ago
-exec ... \; Run a command on each file found (rm in this case)

6. chmod – Change Permissions


bash
CopyEdit
chmod -R 755 foldername
Flag Description
-R Recursively change permissions

7. tar – Archive Files


bash
CopyEdit
tar -czvf backup.tar.gz /path/to/files
Flag Description
-c Create a new archive
-z Compress using gzip
-v Verbose: show files being archived
-f Specify archive filename

8. unzip – Extract ZIP Files


bash
CopyEdit
unzip -q file.zip -d /path
Flag Description
-q Quiet mode (don’t show files)
-d Directory to extract to

9. crontab – Schedule Cron Jobs


bash
CopyEdit
crontab -e
Flag Description
-e Edit crontab entries
-l List crontab entries
Flag Description
-r Remove all crontab entries

10. ps – View Running Processes


bash
CopyEdit
ps aux
Flag Description
a Show processes for all users
u Display user/owner of the process
x Include processes not attached to a terminal

Want a printable cheatsheet or a list of common commands for DevOps, scripting, or


sysadmin tasks?

You said:

Yes
ChatGPT said:

Great! Here's a Linux Command Line Cheatsheet (Printable-Style) for


DevOps/Sysadmin/Scripting tasks — clear, categorized, and beginner-friendly:

Linux Command Line Cheatsheet


1. File & Directory Operations

Command Description
ls -lah List all files with details & sizes
cd /path/to/dir Change directory
pwd Show current directory
mkdir myfolder Create a new folder
rm -rf myfolder Remove a folder & its contents
cp -r src/ dest/ Copy folder recursively
mv oldname newname Move/rename file or folder
touch file.txt Create a new empty file
cat file.txt Display file contents

2. File Compression & Archiving


Command Description
tar -czvf backup.tar.gz /folder Compress folder into .tar.gz
tar -xzvf backup.tar.gz Extract .tar.gz file
zip -r archive.zip /folder Create zip archive
unzip archive.zip -d /destination Extract zip to a folder

3. Searching & Filtering

Command Description
find . -name "*.log" Find files by name
grep "error" file.log Search for text in file
grep -r "token" /var/www Recursively search in directory
find . -type f -mtime +7 -delete Delete files older than 7 days

4. File Permissions

Command Description
chmod +x script.sh Make script executable
chmod 755 file.sh Set file permissions
chown user:group file Change file owner

5. Networking

Command Description
ping google.com Check connectivity
curl -I https://example.com Get HTTP headers
netstat -tulnp List open ports
ss -ltnp Show listening ports
ip a / ifconfig Show IP addresses

6. Disk Usage

Command Description
df -h Show disk space usage
du -sh folder/ Show folder size
`du -ah sort -hr

7. Process & System Monitoring

Command Description
top / htop Real-time system monitoring
Command Description
ps aux List all running processes
kill -9 PID Force kill a process
uptime Show system uptime
free -h RAM usage

8. Cron Jobs (Scheduling)

Command Description
crontab -e Edit cron jobs
crontab -l List user cron jobs
@daily /path/script.sh Run script once a day
*/10 * * * * /script.sh Every 10 minutes

9. System Update & Package Management

Ubuntu/Debian Description
sudo apt update Update package list
sudo apt upgrade Upgrade packages
sudo apt install nginx Install Nginx
sudo apt remove nginx Remove Nginx

10. User & Permissions

Command Description
adduser username Add a new user
passwd username Change password
usermod -aG sudo username Add user to sudo group
whoami Show current user

11. Bash Scripting Shortcuts

Syntax Description
$0, $1, $2... Script args ($0=script, $1=arg1...)
"$@" All passed arguments
$(command) Command substitution
if [ -f file ]; then ... fi Check if file exists
for item in list; do ... done Loop through list

Want it as a PDF Cheatsheet?


I can generate a clean printable PDF if you'd like. Just let me know!

You said:

Chmod 777 and 2777 Describe this values


ChatGPT said:

Great question! Let's break down chmod 777 and chmod 2777 in detail.

1. Understanding File Permissions in Linux


Every file/directory has three types of permissions:

 User (u) – The owner


 Group (g) – The group the file belongs to
 Others (o) – Everyone else

Each permission is represented by:

 r = Read (4)
 w = Write (2)
 x = Execute (1)

These are combined into a three-digit number:


For example:
chmod 7 7 7 → User: rwx, Group: rwx, Others: rwx

2. chmod 777 – Full Access for Everyone


bash
CopyEdit
chmod 777 myfile

Breakdown:

Category Binary Permission


User 7 = 4+2+1 rwx
Group 7 = 4+2+1 rwx
Others 7 = 4+2+1 rwx

 Everyone can read, write, and execute the file.


 Dangerous for scripts or config files, especially on public servers.
3. chmod 2777 – Full Access + Setgid
bash
CopyEdit
chmod 2777 myfolder

Breakdown:

 The first digit (2) is a special permission called Setgid (Set Group ID).
 Followed by 777 as usual.

Setgid (2):

 When applied to a directory, all new files or subdirectories created inside will
inherit the group ownership of that directory (not the creating user's group).
 Useful for collaborative folders (e.g., shared project folder).

Example Use Case of 2777:


bash
CopyEdit
sudo mkdir /shared
sudo chmod 2777 /shared
sudo chgrp developers /shared

 Now, all files created inside /shared will automatically belong to the developers
group.
 Great for teams working in the same folder.

Other Special Permission Bits


Value Bit Meaning
1 Sticky Only owner can delete files (used in /tmp)
2 Setgid Inherit group on new files in a directory
4 Setuid Execute file as file owner (for binaries)

Example:

bash
CopyEdit
chmod 1777 /tmp # Sticky bit + full access
chmod 4755 binary # Setuid + full permissions for owner

Let me know if you want a visual chart or a cheat sheet on permission values!
You said:

give me some linux related interview questions


ChatGPT said:

Absolutely! Here's a categorized list of Linux interview questions — from beginner to


advanced — with a focus on real-world concepts and troubleshooting. Great for DevOps,
sysadmin, or software engineer roles.

✅ Basic Linux Interview Questions


1. What is Linux and how is it different from Unix?
2. What are inodes in Linux?
3. How do file permissions work in Linux?
4. What is the difference between chmod 755 and chmod 777?
5. What does the shebang (#!) mean in shell scripts?
6. What are hard links and soft links?
7. What’s the difference between su and sudo?
8. What is the purpose of /etc/passwd and /etc/shadow?

🔁 File and Directory Management


1. How can you find a file by name?

Example: find / -name filename

2. How do you delete all .log files older than 30 days?

Example: find /var/log -name "*.log" -mtime +30 -delete

3. What is the difference between > and >> in shell?

Permissions and Ownership


1. How do you give read/write/execute permissions to a file?
2. What is the sticky bit and where is it used?
3. Explain SetUID, SetGID with examples.
4. How would you make a directory so that files created inside inherit the group?
🚀 Process Management
1. How do you check running processes?

ps aux, top, htop

2. How do you kill a hanging process by name?

pkill processname

3. What’s the difference between a zombie and orphan process?


4. What is the difference between foreground and background processes?

📦 Package Management (Ubuntu/Debian)


1. How do you install, update, and remove packages?

apt install, apt update, apt remove

2. How can you list all installed packages?

dpkg -l

🔐 User & Group Management


1. How do you add a new user and set their password?
2. How do you add a user to a specific group?

usermod -aG groupname username

3. What is /etc/group and how is it used?

🧠 Cron Jobs and Scheduling


1. What is crontab, and how do you schedule a job every 10 minutes?
2. Where are system-level cron jobs defined?

/etc/crontab, /etc/cron.d/, /etc/cron.daily/


📊 Disk and Memory
1. How do you check disk usage?

df -h

2. How do you check which folders use the most space?

du -sh * | sort -hr

3. How do you monitor RAM and swap usage?

free -h, top

🌐 Networking & Services


1. How do you find your IP address from the command line?
2. What is the difference between netstat, ss, and lsof?
3. How do you restart a service in Ubuntu?

systemctl restart nginx

4. How do you test if a port is open on a remote host?

telnet, nc, or nmap

🧪 Real-World / Troubleshooting
1. A service isn't starting. How do you troubleshoot it?
2. You get a “Permission denied” error running a script. How do you fix it?
3. Website hosted on Nginx is not loading — what steps do you take to debug?
4. You accidentally deleted important files — what can you do next?
5. Disk is full, and you're locked out — how do you clean up space?

🧠 Bonus (Advanced & Conceptual)


1. What is the purpose of the /proc filesystem?
2. How does the Linux boot process work (from BIOS to login prompt)?
3. Explain the concept of runlevels or systemd targets.
4. What is the difference between a shell and a terminal?
5. How do Linux file descriptors work?
Would you like answers for these too, or a formatted PDF with questions and answers? Or I
can make it interactive, like a mock interview style with explanations.

You said:

also gives answer of these questions explain the file & folder structure of linux
ChatGPT said:

Updated saved memory

Awesome! Let’s tackle this in two parts:

🔍 Part 1: File & Folder Structure of Linux (Filesystem


Hierarchy)
In Linux, everything is organized in a tree-like structure starting from the root directory /.

Here's an overview of the most important directories:

Folder Description
/ Root of the entire filesystem. Everything starts here.
/bin Essential user binaries (e.g., ls, cat, cp). Used in single-user mode.
/sbin System binaries (e.g., fsck, reboot). Typically for root/admin use.
/etc Configuration files (e.g., /etc/passwd, /etc/nginx/nginx.conf).
/home User home directories (e.g., /home/john).
/root Home directory of the root user.
/var Variable files — logs (/var/log), mail, spools, etc.
/tmp Temporary files. Often auto-deleted on reboot.
/usr User-installed software and data. Similar to Program Files.
/usr/bin Non-essential user binaries (e.g., compilers, editors).
/usr/sbin Non-essential system binaries (e.g., network daemons).
/lib, /lib64 Shared libraries required by programs in /bin and /sbin.
/opt Optional software installed manually or third-party.
/mnt and /media Mount points for temporary storage/devices like USB, CD-ROMs.
/dev Device files (e.g., /dev/sda1, /dev/null).
/proc Virtual filesystem for process info. (cat /proc/cpuinfo)
/sys Another virtual filesystem. System device and kernel info.
/boot Boot loader files, including the Linux kernel.

🎓 Part 2: Linux Interview Questions with Answers


✅ 1. What is Linux and how is it different from Unix?

Answer:
Linux is an open-source, Unix-like operating system based on the Linux kernel. Unlike
proprietary Unix systems, Linux is freely available and can be modified and distributed. It’s
widely used in servers, desktops, and embedded systems.

✅ 2. What are inodes in Linux?

Answer:
An inode is a data structure that stores metadata about a file — like owner, permissions, size,
and disk location — but not the filename. Filenames are stored in directory entries that point
to inodes.

✅ 3. How do file permissions work in Linux?

Answer:
Permissions are set for:

 User (owner)
 Group
 Others

Each can have:

 Read (r = 4)
 Write (w = 2)
 Execute (x = 1)

Example: chmod 755 file gives rwxr-xr-x:

 User: rwx (7)


 Group: r-x (5)
 Others: r-x (5)

✅ 4. Difference between chmod 755 and chmod 777?

chmod User Group Others Meaning


755 rwx r-x r-x Only owner can write
777 rwx rwx rwx Everyone can do anything (unsafe)

✅ 5. What does #! (shebang) mean in scripts?


Answer:
It's used at the top of a script to specify the interpreter. Example:

bash
CopyEdit
#!/bin/bash

Means the script will run using the Bash shell.

✅ 6. Difference between hard and soft links?

Feature Hard Link Soft Link (Symlink)


Points to Inode Filename
Breaks if original deleted? No Yes
Cross-filesystem? No Yes

✅ 7. Difference between su and sudo?

 su: Switch user (often to root). Requires root password.


 sudo: Execute a command as another user (usually root). Requires your own
password and sudo rights.

✅ 8. What are /etc/passwd and /etc/shadow?

Answer:

 /etc/passwd: Stores user account info (username, UID, GID, home dir).
 /etc/shadow: Stores encrypted passwords and aging info. Only accessible by root.

Would you like me to continue with answers to the remaining questions in the previous list as
well? I can create a PDF-friendly version too if you're preparing for interviews.

You said:

Why double semicolon used here 1) echo "Option 1";; 2) echo "Option 2";;
ChatGPT said:

Great question!

The double semicolon ;; is used in case statements in bash shell scripting, not in regular
command lines.
Here's how it works:
bash
CopyEdit
read -p "Enter a number: " num

case $num in
1) echo "Option 1";;
2) echo "Option 2";;
*) echo "Invalid option";;
esac

Explanation:

 The case statement matches the value of $num.


 Each pattern (1), 2), *) is checked.
 When a match is found, the command after the pattern is executed.
 The ;; tells the shell "end of this case clause" and move out of this pattern block.
 The * is a wildcard pattern — it matches anything not previously matched (like
default in switch-case).

Analogy (like switch in other languages):


c
CopyEdit
switch(x) {
case 1: printf("Option 1"); break;
case 2: printf("Option 2"); break;
default: printf("Invalid");
}

;; in bash is similar to break in C-style switch-case.

Let me know if you want a cheat sheet on control structures like if, for, while, and case.

You said:

Explain the corn timeing, how it managed by 5 star


ChatGPT said:

Sure! Let’s break down cron timing and the meaning of those five stars (* * * * *) in a
cron expression.
What is cron?
cron is a time-based job scheduler in Unix/Linux. It’s used to run scripts or commands
automatically at scheduled times.

Cron Syntax (5-Star Format)


A cron expression has five fields (or sometimes six with seconds), each representing a time
unit:

lua
CopyEdit
* * * * *
| | | | |
| | | | +----- Day of Week (0 - 7) (Sunday is 0 or 7)
| | | +----------- Month (1 - 12)
| | +----------------- Day of Month (1 - 31)
| +----------------------- Hour (0 - 23)
+----------------------------- Minute (0 - 59)

Example:
CopyEdit
30 14 * * 1

 At 2:30 PM on every Monday

What does * mean?


The * is a wildcard and means "every possible value".

Examples:

Cron Meaning
* * * * * Every minute of every hour, day, etc.
0 * * * * At minute 0 (i.e., top of every hour)
0 0 * * * At midnight every day
*/15 * * * * Every 15 minutes
0 12 * * 1-5 At 12:00 PM on weekdays (Mon–Fri)
0 22 * * 1-5 At 10:00 PM, Monday through Friday
0 9 1 * * At 9:00 AM on the first day of each month

Special Strings (Aliases)


Some cron systems support special strings:

String Meaning
@reboot Run once at boot
@daily Every day at midnight
@hourly Every hour
@weekly Every week
@monthly Every month
@yearly Every year (Jan 1)

Bonus: Where to Edit Crons


 Use crontab -e to edit your user’s cron jobs.
 View with crontab -l
 Each user has their own cron.
 System-wide cron files:
o /etc/crontab
o /etc/cron.daily/, /etc/cron.hourly/, etc.

Would you like a table format PDF or image cheat sheet for cron timings?

You said:

kill -9 PID What is -9 specify here, there is any other flag present Explain chgrp command
Kill vs pkill
ChatGPT said:

Great set of questions! Let's break them down clearly:

1. kill -9 PID – What does -9 mean?


kill sends signals to processes.

 -9 is the signal number for SIGKILL, which forcibly kills a process.

Commonly used signals:

Signal Number Name Description


-1 SIGHUP Hangup Reloads configuration (used by daemons)
-2 SIGINT Interrupt Like pressing Ctrl + C
-9 SIGKILL Kill Immediately stops the process (cannot be ignored)
-15 SIGTERM Terminate Graceful shutdown (default signal)
Example:
bash
CopyEdit
kill -15 1234 # Graceful stop
kill -9 1234 # Force kill

2. chgrp command – What does it do?


chgrp is used to change the group ownership of a file or directory.

Syntax:
bash
CopyEdit
chgrp <groupname> <file or directory>

Example:
bash
CopyEdit
chgrp developers report.txt

This changes the group of report.txt to developers.

You can check it using:

bash
CopyEdit
ls -l report.txt

If you want to change group recursively:

bash
CopyEdit
chgrp -R developers /var/www

3. Difference between kill and pkill


Feature kill pkill
Target Needs PID Can target by process name
Example kill -9 1234 pkill -9 nginx
Signal Support Yes (-9, -15, etc.) Yes (same signals apply)
Filtering No filtering beyond PID Can filter by user, terminal, etc.
Use case Known PID Convenient when you only know process name

pkill Examples:
bash
CopyEdit
pkill nginx # Kill all nginx processes
pkill -9 firefox # Force kill all firefox
pkill -u john # Kill all processes by user 'john'
pkill -f script.sh # Match full command line (including script names)

Let me know if you want a cheat sheet of process management tools (top, htop, ps, nice,
kill, pkill, etc.) or a practice set of Linux questions related to processes and permissions.

You said:

Chmod vs chgrp
ChatGPT said:

Great! Let's compare chmod vs chgrp in a clear and simple way:

chmod vs chgrp
Feature chmod chgrp
Purpose Changes permissions of a file or folder Changes group ownership
Full Form Change Mode Change Group
Who it affects User, Group, Others (read/write/execute) Only affects the group assigned
Common usage chmod 755 file.sh chgrp developers file.sh
Used by Owner or root Owner or root
Recursive Option -R for recursive changes -R for recursive group change

Example Use Case:

chmod – Set access rules:

bash
CopyEdit
chmod 755 script.sh
# Owner can read/write/execute, others can read and execute

chgrp – Assign group ownership:

bash
CopyEdit
chgrp admin script.sh
# Now the group 'admin' owns the file

You can view ownership and permissions using:

bash
CopyEdit
ls -l script.sh
Example output:

diff
CopyEdit
-rwxr-xr-x 1 root admin 1234 Apr 17 12:00 script.sh

 root is the owner.


 admin is the group (modified by chgrp).
 rwxr-xr-x is permission (modified by chmod).

Summary:

 Use chmod to control what users/groups/others can do (read/write/execute).


 Use chgrp to control which group owns the file or directory.

Let me know if you want a practical hands-on mini project involving both!

You said:

What is the difference between > and >> in shell? How do you find your IP address from the
command line? What is the sticky bit and where is it used? Explain SetUID, SetGID with
examples. How would you make a directory so that files created inside inherit the group? A
service isn't starting. How do you troubleshoot it? You get a “Permission denied” error
running a script. How do you fix it? Website hosted on Nginx is not loading — what steps do
you take to debug? You accidentally deleted important files — what can you do next? Disk is
full, and you're locked out — how do you clean up space? What is the purpose of the /proc
filesystem? How does the Linux boot process work (from BIOS to login prompt)? Explain
the concept of runlevels or systemd targets. What is the difference between a shell and a
terminal? How do Linux file descriptors work?
ChatGPT said:

Updated saved memory

Great questions — you're diving into real system admin territory now! Let’s go through each
one with concise yet detailed answers:

1. > vs >> in Shell

 > : Overwrites a file with new content.

bash
CopyEdit
echo "Hello" > file.txt # file.txt now only has "Hello"

 >> : Appends to the file.


bash
CopyEdit
echo "World" >> file.txt # Adds "World" to the end

2. Find Your IP Address

 Internal IP:

bash
CopyEdit
ip a

or

bash
CopyEdit
hostname -I

 External IP:

bash
CopyEdit
curl ifconfig.me

3. Sticky Bit

 Prevents users from deleting files in a shared directory unless they own them.
 Common in /tmp.

bash
CopyEdit
chmod +t /sharedfolder
ls -ld /sharedfolder # Note the 't' at the end of permissions

4. SetUID & SetGID

 SetUID (s on user): Runs file as file owner (usually root).

bash
CopyEdit
chmod u+s file

Example: passwd command uses SetUID to modify /etc/shadow.

 SetGID (s on group):
o On file: Run with group permissions.
o On directory: Files inherit parent directory's group.

bash
CopyEdit
chmod g+s /project
ls -ld /project # Notice the 's' in group permission

5. Inherit Group in Directory


bash
CopyEdit
chgrp devteam /mydir
chmod g+s /mydir

Now files created in /mydir will have group devteam.

6. Service Isn’t Starting – Troubleshooting Steps

1. Check status:

bash
CopyEdit
systemctl status myservice

2. View logs:

bash
CopyEdit
journalctl -xeu myservice

3. Test manually:
o Check ports, dependencies, permissions.
4. Validate config files:

bash
CopyEdit
nginx -t

7. “Permission Denied” Running Script

1. Check permissions:

bash
CopyEdit
ls -l script.sh

2. Make executable:

bash
CopyEdit
chmod +x script.sh

3. Ensure correct interpreter at top (#!/bin/bash).


8. Nginx Website Not Loading – Debugging Steps

1. Test server:

bash
CopyEdit
curl http://localhost

2. Check Nginx status:

bash
CopyEdit
systemctl status nginx
nginx -t

3. Check logs:
o /var/log/nginx/error.log
4. Check firewall (ufw, iptables).
5. Validate DNS, domain config.

9. Deleted Important Files — What to Do?

 Check:
o Trash (~/.local/share/Trash)
o Backups
o Disk recovery tools:

bash
CopyEdit
testdisk, extundelete

 Stop writing to disk immediately.

10. Disk Full & Locked Out

1. Boot into recovery mode or use a live USB.


2. Mount disk, delete large logs or temp files:

bash
CopyEdit
du -shx /* 2>/dev/null | sort -h
rm -rf /var/log/*.gz

3. Clear cache:

bash
CopyEdit
apt clean

11. /proc Filesystem

 Virtual filesystem exposing kernel & process information.


 Examples:
o /proc/cpuinfo – CPU details
o /proc/meminfo – Memory usage
o /proc/<PID> – Per-process info

12. Linux Boot Process (BIOS to Login)

1. BIOS/UEFI – Loads bootloader.


2. GRUB – Loads kernel.
3. Kernel – Initializes hardware, mounts /
4. Init/Systemd – Starts services and targets.
5. Login Prompt (TTY or GUI) – User logs in.

13. Runlevels vs Systemd Targets

 Runlevels (SysV):
o 0 = Halt
o 1 = Single-user
o 3 = Multi-user (text)
o 5 = GUI
o 6 = Reboot
 Systemd Targets (modern systems):
o runlevel3.target = multi-user.target
o runlevel5.target = graphical.target
o View with:

bash
CopyEdit
systemctl get-default

14. Shell vs Terminal

 Shell: Command-line interpreter (e.g., bash, zsh).


 Terminal: The software interface that lets you interact with the shell (e.g., GNOME
Terminal, xterm).
15. File Descriptors

 Every process has file descriptors:


o 0 = stdin
o 1 = stdout
o 2 = stderr

You can redirect:

bash
CopyEdit
command > out.txt 2>&1 # stdout and stderr to out.txt

You might also like