Shell Scripting Interview
Shell Scripting Interview
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:
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.
#!/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
2. Shebang (#!)
The first line of a shell script is usually the shebang line.
sh
CopyEdit
#!/bin/bash
3. Comments
sh
CopyEdit
# This is a comment
4. Variables
Declare and use variables:
sh
CopyEdit
name="Alice"
echo "Hello, $name"
No spaces around =.
Access using $variable_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"
sh
CopyEdit
a=5
b=3
sum=$((a + b))
echo "Sum is $sum"
0means success
Non-zero means error
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.
bash
CopyEdit
chmod +x backup_mysql.sh
Step 2: Schedule It Using Cron
Open the crontab:
bash
CopyEdit
crontab -e
This means:
sql
CopyEdit
Minute Hour Day Month Weekday Command
0 2 * * * Run daily at 2 AM
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)
You said:
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.
Real-Life Analogy
"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.
sh
CopyEdit
find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7
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:
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
Option Description
-atime +1 Last accessed more than 1 day ago
-amin -15 Last accessed within the last 15 minutes
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.
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.
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"
Explanation:
bash
CopyEdit
0 2 * * * /home/ubuntu/backup_mysql.sh
Your server fills up with log files and stops working. You need a script that:
Script:
bash
CopyEdit
#!/bin/bash
Explanation:
You receive files in /incoming/ folder with unclear names like data.csv. You want to:
Script:
bash
CopyEdit
#!/bin/bash
SRC_DIR="/home/ubuntu/incoming"
DEST_DIR="/home/ubuntu/processed"
TIMESTAMP=$(date +%F_%H-%M)
Explanation:
Want More?
Would you like:
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?
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.
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
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")
Explanation:
bash
CopyEdit
*/5 * * * * /home/ubuntu/monitor_service.sh
Problem: You want to send reminders for upcoming birthdays stored in a file.
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:
Problem: You generate daily reports and want to zip them after 3 days.
Script:
bash
CopyEdit
#!/bin/bash
REPORT_DIR="/home/ubuntu/reports"
Explanation:
Want me to generate:
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
bash
CopyEdit
fruits=("apple" "banana" "cherry")
fruits[0] → apple
fruits[1] → banana
fruits[2] → cherry
bash
CopyEdit
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done
You can now loop or process them just like any static array.
report1.txt → backup_report1.txt
data.csv → backup_data.csv
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.
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
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:
bash
CopyEdit
chmod +x todo_manager.sh
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!
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).
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:
bash
CopyEdit
chmod +x todo_manager.sh
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!
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.
bash
CopyEdit
#!/bin/bash
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"
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
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.
Next Steps:
You said:
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 5: Clean up
rm -rf "$TMP_DIR"
How to Use:
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:
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
You said:
Yes
ChatGPT said:
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
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
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
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
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
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
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
You said:
Great question! Let's break down chmod 777 and chmod 2777 in detail.
r = Read (4)
w = Write (2)
x = Execute (1)
Breakdown:
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).
Now, all files created inside /shared will automatically belong to the developers
group.
Great for teams working in the same folder.
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:
pkill processname
dpkg -l
df -h
🧪 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?
You said:
also gives answer of these questions explain the file & folder structure of linux
ChatGPT said:
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.
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.
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.
Answer:
Permissions are set for:
User (owner)
Group
Others
Read (r = 4)
Write (w = 2)
Execute (x = 1)
bash
CopyEdit
#!/bin/bash
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:
Let me know if you want a cheat sheet on control structures like if, for, while, and case.
You 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.
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
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
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)
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:
Syntax:
bash
CopyEdit
chgrp <groupname> <file or directory>
Example:
bash
CopyEdit
chgrp developers report.txt
bash
CopyEdit
ls -l report.txt
bash
CopyEdit
chgrp -R developers /var/www
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:
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
bash
CopyEdit
chmod 755 script.sh
# Owner can read/write/execute, others can read and execute
bash
CopyEdit
chgrp admin script.sh
# Now the group 'admin' owns the file
bash
CopyEdit
ls -l script.sh
Example output:
diff
CopyEdit
-rwxr-xr-x 1 root admin 1234 Apr 17 12:00 script.sh
Summary:
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:
Great questions — you're diving into real system admin territory now! Let’s go through each
one with concise yet detailed answers:
bash
CopyEdit
echo "Hello" > file.txt # file.txt now only has "Hello"
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
bash
CopyEdit
chmod u+s file
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
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
1. Check permissions:
bash
CopyEdit
ls -l script.sh
2. Make executable:
bash
CopyEdit
chmod +x script.sh
1. Test server:
bash
CopyEdit
curl http://localhost
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.
Check:
o Trash (~/.local/share/Trash)
o Backups
o Disk recovery tools:
bash
CopyEdit
testdisk, extundelete
bash
CopyEdit
du -shx /* 2>/dev/null | sort -h
rm -rf /var/log/*.gz
3. Clear cache:
bash
CopyEdit
apt clean
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
bash
CopyEdit
command > out.txt 2>&1 # stdout and stderr to out.txt