Note:
- You need to create the shell script file using touch command
sudo touch script.sh
2. Make it executable using below command or directly run using the command
sudo chmod +x script.sh
./script.sh
OR
bash script.sh
1. How do you print “Hello, World!” in a Bash script?
Ans:
echo "hello world"
2. How do you create a variable and print its value?
Ans:
name="Ashish"
echo $name
3. How do you read user input into a variable?
Ans:
read -p "Enter you name: " name
echo "Hello, $name"
4. Write a script to add two numbers provided as command-line arguments?
Ans:
#!/bin/bash
sum=$(($1 + $2))
echo "Sum: $sum"
5. How do you check if a file exists and is readable?
Ans:
#!/bin/bash
if [ -r file.txt ]; then
echo "File is readable"
else
echo "File is not readable"
fi
6. Write a script to check if a number is even or odd?
Ans:
#!/bin/bash
if [ $(($1 % 2)) -eq 0 ]; then
echo "Number is even"
else
echo "Number is Odd"
fi
7. How do you print numbers from 1 to 10 using a for loop?
Ans:
for i in {1,2,3,4,5,6,7,8,9,10}; do
echo $i
done
8. Write a script to print all files in the current directory?
Ans:
#!/bin/bash
for file in *; do
echo $file
done
9. How do you use a while loop to print numbers from 10 to 1?
Ans:
#!/bin/bash
i=101.
10. Write a script to count the number of lines in a file?
Ans:
#!/bin/bash
lines=$(wc -l < files.txt)
echo "Numbers of lines: $lines"
11. How do you append or add text to a file?
Ans:
echo "This is linux world" >> files.txt
12. Write a script to find the largest number in an array?
Ans:
#!/bin/bash
numbers= (3 5 7 9 11 )
max=${numbers[0]}
for n in "${numbers[@]}"; do
if [[$n -gt $max]]; then
fi
done
echo "Max number is: $max"
13. How do you perform arithmetic operations in Bash?
Ans:
#!/bin/bash
result= $((3 + 5 * 2))
echo "Result is: $result"
14. Write a script to monitor disk usage and send an alert if it exceeds 80%?
Ans:
usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
if [ $usage -gt 80 ]; then
echo "Disk usage is above 80%!"
fi
15. How do you check if a server is reachable?
Ans:
#!/bin/bash
ping -c 1 google.com &> /dev/null
if [ $? -eq 0 ]; then
echo "Server is reachable"
else
echo "Server is unreachable"
fi
16. Write a script to download a file from the internet?
Ans:
#!/bin/bash
url="https://example.com/files.txt"
wget $url
17. Write a script to check if a user exists on the system?
Ans:
#!/bin/bash
if id "username" &> /dev/null; then
echo "user exists"
else
echo "user does not exists"
done
18. Write a script to check if a process is running and start it if not?
Ans:
if ! pgrep -x "process_name" > /dev/null; then
process_name &
fi
19. How do you view the last 10 lines of a log file?
Ans:
tail -n 10 /var/log/syslog
19. Write a script to monitor a log file for a specific keyword?
Ans:
tail -f /var/log/syslog | grep --line-buffered "ERROR"
20. How do you schedule a script to run every day at 2 AM?
Ans:
crontab -e
# Add the following line
0 2 * * * /path/to/script.sh
21. Write a script to list all cron jobs for the current user?
Ans:
crontab -l
22. How do you find all lines containing a specific word in a file?
Ans:
grep "word" files.txt
23. Write a script to replace all occurrences of “foo” with “bar” in a file?
Ans:
sed -i 's/foo/bar/g' files.txt
24. How do you display the IP address of the system?
Ans:
hostname -I
25. How do you automatically delete files older than 7 days in a directory?
Ans:
find /var/www/ -type f -mtime +7 -exec rm {} \;
26. Write an bash script to automate the process of creating a MySQL dump, compressing it with a timestamp, uploading it to an AWS S3 bucket, and cleaning up older backup files?
Ans:
Pre-requisites:
- AWS CLI installed and configured with the necessary permissions to access the S3 bucket.
- S3 Bucket should be already created in the aws account
- Mysql Client installed on the server
#!/bin/bash
#write an variables
DB_USER="mysql"
DB_PASSWORD= "mysql_password"
DB_NAME= "database_name"
BACKUP_DIR="/path/to/backup/dir"
S3_BUCKET= "your_s3_bucket_name"
TIMESTAMP= $(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/$DB_NAME-$TIMESTAMP.sql"
TAR_FILE= "$BACKUP_DIR/$DB_NAME-$TIMESTAMP.tar.gz"
# Create mysql dump
echo "Creating mysql dump ...."
mysqldump -u $DB_USER -p $DB_PASSWORD $DB_NAME > $BACKUP_FILE
# Check if dump was succesful or not
if [ $? -ne 0 ]; then
echo "Mysql Dump Failed"
exit 1
fi
# Compress the backup file
echo "Compressing backup file..."
tar -czvf $TAR_FILE -C $BACKUP_DIR $(basename $BACKUP_FILE)
# Remove the uncompressed SQL dump
rm $BACKUP_FILE
# Upload the tar file to S3
echo "Uploading backup to S3..."
aws s3 cp $TAR_FILE s3://$S3_BUCKET/
# Check if upload was successful
if [ $? -ne 0 ]; then
echo "Failed to upload backup to S3!"
exit 1
fi
# Delete tar files older than 7 days
echo "Deleting old backup files..."
find $BACKUP_DIR -type f -name "*.tar.gz" -mtime +7 -exec rm {} \;
echo "Backup completed successfully!"
Explanation
- Variables:
DB_USER
,DB_PASSWORD
,DB_NAME
: MySQL credentials and database name.BACKUP_DIR
: Directory to store the backup files.S3_BUCKET
: AWS S3 bucket name.TIMESTAMP
: Current date and time for the backup file naming.
- Create MySQL Dump:
- Uses
mysqldump
to create a dump of the specified database. - Checks if the dump was successful and exits if not.
- Uses
- Compress the Backup File:
- Uses
tar
to compress the SQL dump file with a timestamp. - Deletes the uncompressed SQL dump file after creating the tar file.
- Uses
- Upload to S3:
- Uses
aws s3 cp
to upload the compressed backup file to the specified S3 bucket. - Checks if the upload was successful and exits if not.
- Uses
- Delete Old Backup Files:
- Uses
find
to locate and delete tar files older than 7 days in the backup directory.
- Uses
Running the Script
- Make the script executable:bashCopy code
chmod +x mysql_backup.sh
- Run the script:bashCopy code
./mysql_backup.sh
Scheduling with Cron
To automate this script, you can schedule it to run periodically using cron:
- Edit the crontab:bashCopy code
crontab -e
- Add a cron job (e.g., to run the script every day at 2 AM):bashCopy code
0 2 * * * /path/to/mysql_backup.sh
By using this script, you can ensure regular backups of your MySQL database, safe storage in AWS S3, and automated cleanup of old backups.
27. How to automate the cleaning cache memory?
Ans:
#!/bin/bash
free -wh > ~/old
purging () {
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches}
report(){
echo -e "\n\n\n\nServer $(curl -s -4 ident.me;echo)'s cache Purging report:-\n-----Before Purging-- --\n$(cat ~/old)\n\n-----After Purging-----\n$(free -wh)\nTimeStamp:- $(TZ='Asia/Kolkata' date)\n\n"
}
purging > /dev/null 2>&1 && report || echo -e "Kindly run with sudo rights\nExample:- sudo mfree"
!/bin/bash: This is the shebang line, which tells the operating system to use the Bash shell to
interpret and execute the following script.
free -wh > ~/old:
- This line executes the free command with options -w (human-readable) and – h (kilobytes).
- The output is redirected to a file named old in the user’s home directory.
- This creates a snapshot of memory usage before the purging process, serving as a reference point for comparison.
purging () { … }:
- This defines a function named purging.
- The function body contains multiple lines:
- sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches: This line attempts to free various levels of cached memory by:
- sudo sync: Forces the system to write all data from memory to disk.
- sudo echo 1 > /proc/sys/vm/drop_caches: Tells the kernel to drop unused page cache entries.
- This command is repeated multiple times with values 2 and 3, aiming to progressively free more memory. However, it’s crucial to understand that this can significantly impact system performance if done aggressively.
- sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches: This line attempts to free various levels of cached memory by:
report () { … }:
- This defines a function named report.
- The function constructs a multi-line report containing:
- Server identification using curl and ident.me.
- Memory usage before purging, retrieved from the old file.
- Memory usage after purging, obtained by running free.
- Timestamp formatted for India timezone (Asia/Kolkata).
purging > /dev/null 2>&1 && report || echo -e “Kindly run with sudo rights\nExample:- sudo mfree”:
- This line attempts to run the purging function.
- /dev/null: Discards the standard output, preventing it from cluttering the terminal
- 2>&1: Redirects standard error to standard output, allowing both outputs to be handled together.
- If the function execution succeeds (&&), the report function is called to generate a report
- If the function fails due to insufficient permissions (||), an error message explaining the need for sudo rights and an example usage is displayed.
Important Cautions:
- Execute with caution: Aggressive cache clearing can negatively impact system performance. Consider alternative approaches like targeted cache invalidation or memory management tools.
- Understand the implications: Executing scripts with sudo grants elevated privileges. Thoroughly understand the script’s behaviour and potential consequences before running it.
- Seek professional guidance: Complex system administration tasks may require expert intervention. If unsure, consult a qualified professional.
If you want to execute this script on every Sunday at 6pm then you can update like this in crontab:
0 18 * * 0 /path/to/your/script.sh
Explanation:
0: Minute (0 represents 6pm)
18: Hour (24-hour format; 18 corresponds to 6pm)
*: Day of month (ignored since we specify day of week)
*: Month (ignored since we specify day of week)
0: Day of week (0 or 7 both represent Sunday)
/path/to/your/script.sh: The path to your script file
28. How to automate log rotation of mongodb database installed on linux server?
Ans:
#!/bin/bash
#Script Name: Mongodb_log_rotate_and_cleanup.sh
# Define MongoDB connection details (improve security with secrets management)
MONGODB_USERNAME="<USERNAME>"
MONGODB_PASSWORD="<PASSWORD>" # Consider using environment variables or a secure store
# Trigger MongoDB log rotation
mongo_command="db.adminCommand({ logRotate: 1 })"
mongosh --eval "$mongo_command" -u "$MONGODB_USERNAME" -p "$MONGODB_PASSWORD"
# Wait for log rotation to complete (adjust based on expected rotation time)
sleep 120
# Define search criteria for old log files
log_dir="/var/log/mongodb/"
log_prefix="mongod.log.2024"
max_file_age=5 # Files older than 5 days will be removed
# Find and delete old log files
find "$log_dir" -name "$log_prefix*" -mtime +"$max_file_age" -exec rm -rf {} \;
echo "MongoDB log rotation and cleanup completed."
Script Explanation:
MONGODB_USERNAME=”” and MONGODB_PASSWORD=”: These lines define variables to store the MongoDB username and password. These credentials are used to authenticate with the MongoDB instance.
mongo_command=”db.adminCommand({ logRotate: 1 })”: This line defines a variable mongo_command which stores the MongoDB command to rotate logs. The logRotate command is a MongoDB command to initiate log rotation.
mongosh –eval “$mongo_command” -u “$MONGODB_USERNAME” -p “$MONGODB_PASSWORD”: This line executes the MongoDB command stored in the mongo_command variable using the mongosh shell. It passes the MongoDB username and password for authentication.
sleep 120: This line pauses the script execution for 120 seconds (2 minutes) to allow time for the log rotation process to complete. The duration of the sleep can be adjusted based on the expected time for log rotation.
log_dir=”/var/log/mongodb/”, log_prefix=”mongod.log.2024″, and max_file_age=5: These lines define variables to store the directory where MongoDB log files are located (log_dir), the prefix of the log file names (log_prefix), and the maximum age (in days) of log files to retain (max_file_age).
find “$log_dir” -name “$log_prefix*” -mtime +”$max_file_age” -exec rm -rf {} \;: This line uses the find command to search for log files in the specified directory (log_dir) that match the specified prefix (log_prefix) and are older than the specified maximum age (max_file_age). It then executes the rm -rf command to remove those files.
echo “MongoDB log rotation and cleanup completed.”: This line prints a message to indicate that the MongoDB log rotation and cleanup process has been completed.
30. How to automate the ssl certificate renewal for a website on linux server?
Ans:
#!/bin/bash
# Define domain and email variables
DOMAIN="devops-ocean.com"
EMAIL="contact@devops-ocean.com"
# Define the path to the Let's Encrypt script
LE_SCRIPT="/usr/bin/certbot"
# Define the path to the SSL certificate
CERTIFICATE_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
# Define the path to the certificate renewal log file
LOG_FILE="/var/log/certbot-renewal.log"
# Check if the certificate needs renewal
if ! $LE_SCRIPT renew --dry-run > $LOG_FILE 2>&1; then
# Certificate needs renewal, execute renewal
echo "$(date +"%Y-%m-%d %H:%M:%S") - Certificate for $DOMAIN needs renewal" >> $LOG_FILE
# Execute certificate renewal
$LE_SCRIPT renew --noninteractive --agree-tos --email $EMAIL >> $LOG_FILE 2>&1
# Check if renewal was successful
if [ $? -eq 0 ]; then
echo "$(date +"%Y-%m-%d %H:%M:%S") - Certificate for $DOMAIN successfully renewed" >> $LOG_FILE
# Restart web server to apply changes
systemctl restart nginx
else
echo "$(date +"%Y-%m-%d %H:%M:%S") - Certificate renewal for $DOMAIN failed" >> $LOG_FILE
fi
else
# Certificate doesn't need renewal
echo "$(date +"%Y-%m-%d %H:%M:%S") - Certificate for $DOMAIN is up to date, no renewal needed" >> $LOG_FILE
fi
!/bin/bash: This line is called a shebang and indicates that the script should be executed using the Bash shell.
Comments: Lines starting with # are comments and are ignored by the shell. They are used to provide information about the script, such as its purpose, author, and date.
Domain and Email Configuration: The script begins by defining variables for the domain name (DOMAIN) for which the SSL certificate is issued and the email address (EMAIL) associated with the certificate.
Let’s Encrypt Script Path: The script specifies the path to the Let’s Encrypt script (certbot). This script is responsible for certificate management, including renewal.
Certificate Path: The path to the SSL certificate (CERTIFICATE_PATH) is defined. This certificate path is typically where Let’s Encrypt stores the certificate files.
Log File Path: A path to a log file (LOG_FILE) is specified. This log file will contain information about the certificate renewal process.
Checking Certificate Renewal: The script uses the –dry-run option with certbot to check if the certificate needs renewal. This option performs a test renewal without actually updating the certificate.
Certificate Renewal Process: If the dry-run indicates that renewal is needed, the script executes the certificate renewal process non-interactively (–noninteractive), agreeing to the Let’s Encrypt terms of service (– agree-tos) and providing the email address for notifications (–email).
Handling Renewal Outcome: If the renewal process is successful, the script logs the event and restarts the web server to apply the changes. If the renewal fails, the script logs the failure.
Logging: Throughout the script, various actions and outcomes are logged to the log file specified earlier. This helps in tracking the certificate renewal process and troubleshooting any issues