0% found this document useful (0 votes)
8 views15 pages

How To Create A Bash Script That Only Executes From Cron - by Konstantinos Patronas - Nov, 2024 - Medium

Uploaded by

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

How To Create A Bash Script That Only Executes From Cron - by Konstantinos Patronas - Nov, 2024 - Medium

Uploaded by

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

How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24,

4, 9:44 AM

25 Python Scripts to Boost Your


Productivity
Neuro Bytes

Python is a powerful productivity boosting tool! it helps you save time,


reduce errors, and focus on more important work.

1. Automated File Renaming Script


Renaming a large number of files manually can be tedious. This Python
script automates the process, making it simple to rename files based on a
pattern.

import os

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 1 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

def rename_files(directory, prefix):


for count, filename in enumerate(os.listdir(directory), start=1):
new_name = f"{prefix}_{count}{os.path.splitext(filename)[1]}"
os.rename(os.path.join(directory, filename), os.path.join(direc
# Usage
rename_files('/path/to/your/folder', 'document')

Use case: Automatically rename files in a folder, such as for organizing


photos or documents.

2. Automated File Backup Script


Backing up important files is crucial for data protection. This script copies
specific files or folders to a backup location.

import shutil
import os

def backup_files(src_dir, dest_dir):


if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
for item in os.listdir(src_dir):
s = os.path.join(src_dir, item)
d = os.path.join(dest_dir, item)
if os.path.isdir(s):
shutil.copytree(s, d, dirs_exist_ok=True)
else:
shutil.copy2(s, d)
# Usage
backup_files('/path/to/your/folder', '/path/to/backup/folder')

Use case: Automatically back up files and folders to prevent data loss.

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 2 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

3. Send Automated Emails Script


Send pre-configured emails automatically with the help of Python’s smtplib
library.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email):


from_email = "[email protected]"
password = "yourpassword"
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
# Usage
send_email("Test Subject", "This is the body of the email.", "recipient

Use case: Send automated daily reports, reminders, or newsletters.

4. Web Scraping Script for Data Collection


Web scraping allows you to extract data from websites. Here’s how you can
use the requests and BeautifulSoup libraries to scrape web data.

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 3 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for headline in soup.find_all('h2'):
print(headline.get_text())
# Usage
scrape_website('https://example.com/news')

Use case: Automatically collect data such as news headlines, product


prices, or stock information.

5. Automatic Text File Formatter


Format your text files to make them more readable and consistent. This
script removes extra spaces and aligns text properly.

def format_text_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
formatted_lines = [line.strip() for line in lines if line.strip()]
with open(file_path, 'w') as file:
file.write('\n'.join(formatted_lines))
# Usage
format_text_file('large_text_file.txt')

Use case: Clean and format text files like logs, reports, or configuration files.

6. Reminder & Calendar Integration

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 4 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

This script connects to Google Calendar and sets reminders for upcoming
events.

import datetime
import webbrowser

def set_reminder(event_time, event_name):


current_time = datetime.datetime.now()
time_diff = event_time - current_time
if time_diff.days >= 0:
print(f"Reminder set for {event_name} at {event_time}")
# You can also use a web browser to open the Google Calendar UR
# webbrowser.open('https://calendar.google.com')
else:
print("Event time has passed")
# Usage
event_time = datetime.datetime(2024, 11, 15, 9, 30) # Set your event t
set_reminder(event_time, "Team Meeting")

Use case: Set reminders for meetings, appointments, or any important


tasks.

7. Password Generator Script


Create strong, random passwords using Python.

import random
import string

def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuat
password = ''.join(random.choice(characters) for i in range(length)
return password

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 5 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

# Usage
print(generate_password(16))

Use case: Generate strong and secure passwords for your online accounts.

8. Batch Image Resizer


Resize multiple images at once using the Pillow library.

from PIL import Image


import os

def resize_images(directory, size=(800, 800)):


for filename in os.listdir(directory):
if filename.endswith(('.jpg', '.jpeg', '.png')):
image_path = os.path.join(directory, filename)
with Image.open(image_path) as img:
img = img.resize(size)
img.save(image_path)
# Usage
resize_images('/path/to/your/images')

Use case: Automatically resize images for websites or social media


platforms.

9. Data Analysis Automation


Automate your data processing and analysis tasks using Pandas.

import pandas as pd
def analyze_data(file_path):
df = pd.read_csv(file_path)

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 6 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

print(df.describe()) # Get summary statistics


print(df.corr()) # Get correlation matrix
# Usage
analyze_data('sales_data.csv')

Use case: Automatically analyze data and generate reports or insights.

10. Automated Task Scheduling


Use Python to schedule tasks to run at specific intervals with the schedule
library.

import schedule
import time

def job():
print("Task executed!")
schedule.every(10).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)

Use case: Automate recurring tasks like checking for new emails or running
data updates.

11. Automated PDF Merge


This script merges multiple PDFs into one, which can be helpful for
organizing documents.

from PyPDF2 import PdfMerger

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 7 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

def merge_pdfs(pdf_list, output_path):


merger = PdfMerger()
for pdf in pdf_list:
merger.append(pdf)
merger.write(output_path)
merger.close()
# Usage
merge_pdfs(['file1.pdf', 'file2.pdf'], 'merged_output.pdf')

Use case: Combine multiple PDF reports or documents into one file.

12. Monitor Website Availability


Check if a website is up or down by sending a simple HTTP request.

import requests
def check_website_status(url):
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Website {url} is up!")
else:
print(f"Website {url} is down!")
except requests.exceptions.RequestException as e:
print(f"Error checking {url}: {e}")
# Usage
check_website_status('https://example.com')

Use case: Monitor website availability and get notified if a site goes down.

13. CSV to Excel Converter


Convert CSV files into Excel format using Python.
https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 8 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

import pandas as pd

def csv_to_excel(csv_file, excel_file):


df = pd.read_csv(csv_file)
df.to_excel(excel_file, index=False)
# Usage
csv_to_excel('data.csv', 'data.xlsx')

Use case: Convert CSV data files into Excel files for better formatting and
analysis.

14. Auto Tweet Script


Automate your Twitter posts using the Tweepy library.

import tweepy
def auto_tweet(message, api_key, api_secret_key, access_token, access_t
auth = tweepy.OAuth1UserHandler(api_key, api_secret_key, access_tok
api = tweepy.API(auth)
api.update_status(message)
# Usage
auto_tweet("Hello World! #Python", 'API_KEY', 'API_SECRET_KEY', 'ACCESS

Use case: Schedule automatic tweets for announcements or updates.

15. Clipboard Manager Script


This script stores clipboard history and allows you to access previous
clipboard entries.

import pyperclip

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 9 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

clipboard_history = []
def store_clipboard():
text = pyperclip.paste()
clipboard_history.append(text)
def show_history():
for index, entry in enumerate(clipboard_history):
print(f"{index+1}. {entry}")
# Usage
store_clipboard()
show_history()

Use case: Track and manage your clipboard history for easier copy-paste
operations.

16. Batch PDF to Image Converter


Convert multiple PDF pages into images using pdf2image.

from pdf2image import convert_from_path


def pdf_to_images(pdf_file):
images = convert_from_path(pdf_file)
for i, image in enumerate(images):
image.save(f'output_page_{i}.png', 'PNG')
# Usage
pdf_to_images('document.pdf')

Use case: Convert PDF documents into images for presentations or web
use.

17. Automated Calendar Event Creation


Create Google Calendar events directly from Python.

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 10 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

import datetime
import pytz
def create_event(event_time, event_name):
# This would use Google Calendar API to create an event
pass # Implement authentication and calendar API call here
# Usage
create_event(datetime.datetime(2024, 11, 15, 9, 30), "Team Meeting")

Use case: Automatically schedule events on your Google Calendar.

18. Website Traffic Analyzer


Use Python to analyze traffic logs from websites.

from collections import Counter

def analyze_traffic(log_file):
with open(log_file, 'r') as file:
lines = file.readlines()
ip_addresses = [line.split()[0] for line in lines]
ip_counts = Counter(ip_addresses)
print(ip_counts)
# Usage
analyze_traffic('access_log.txt')

Use case: Analyze website traffic and identify frequent visitors or potential
issues.

19. File Type Counter


Count the types of files in a directory (e.g., how many .txt, .jpg files are

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 11 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

there).

import os

def count_file_types(directory):
file_types = {}
for filename in os.listdir(directory):
ext = os.path.splitext(filename)[1]
file_types[ext] = file_types.get(ext, 0) + 1
print(file_types)
# Usage
count_file_types('/path/to/your/folder')

Use case: Get an overview of the types of files in a directory.

20. JSON Data to CSV Converter


Convert JSON data to CSV for easier manipulation.

import pandas as pd
import json

def json_to_csv(json_file, csv_file):


with open(json_file) as file:
data = json.load(file)
df = pd.DataFrame(data)
df.to_csv(csv_file, index=False)
# Usage
json_to_csv('data.json', 'output.csv')

Use case: Convert JSON data into CSV for easier analysis in spreadsheet
tools.

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 12 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

21. Social Media Status Checker


Automatically check the status of your social media accounts (e.g., if they
are online or down).

import requests

def check_social_media_status(url):
response = requests.get(url)
if response.status_code == 200:
print(f"{url} is up")
else:
print(f"{url} is down")
# Usage
check_social_media_status('https://twitter.com')

Use case: Monitor the availability of social media platforms or other


websites.

22. Currency Converter


Convert currencies using live exchange rates.

import requests

def convert_currency(amount, from_currency, to_currency):


url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
response = requests.get(url).json()
exchange_rate = response['rates'][to_currency]
return amount * exchange_rate
# Usage
print(convert_currency(100, 'USD', 'EUR'))

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 13 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

Use case: Convert currency based on live exchange rates for travel or
financial purposes.

23. Automated System Monitor


Monitor CPU and memory usage on your system.

import psutil

def monitor_system():
print(f"CPU usage: {psutil.cpu_percent()}%")
print(f"Memory usage: {psutil.virtual_memory().percent}%")
# Usage
monitor_system()

Use case: Monitor system performance and resource usage in real time.

24. Directory Organizer


Automatically organize files in a directory based on their type.

import os
import shutil

def organize_directory(directory):
for filename in os.listdir(directory):
ext = os.path.splitext(filename)[1][1:]
folder = os.path.join(directory, ext)
if not os.path.exists(folder):
os.makedirs(folder)
shutil.move(os.path.join(directory, filename), os.path.join(fol

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 14 of 15
How to Create a Bash Script That Only Executes from Cron | by Konstantinos Patronas | Nov, 2024 | Medium 11/16/24, 9:44 AM

# Usage
organize_directory('/path/to/your/folder')

Use case: Keep your directories organized by automatically sorting files into
subfolders based on file type.

25. Automated Social Media Poster


Post updates automatically to your social media accounts using APIs.

import tweepy

def post_tweet(api_key, api_secret_key, access_token, access_token_secr


auth = tweepy.OAuth1UserHandler(api_key, api_secret_key, access_tok
api = tweepy.API(auth)
api.update_status(message)
# Usage
post_tweet('API_KEY', 'API_SECRET_KEY', 'ACCESS_TOKEN', 'ACCESS_TOKEN_S

Use case: Schedule and post updates automatically to Twitter, Facebook,


etc.

In Conclusion
Woohooow! Congratulations! , you have now boosted your productivity
300%!!

I’m leaving you here with some of the best scripts I have written and I am
using on a daily basis to boost my productivity and to save me time and to
automate things as well. you can improve these scripts the way you want
and get creative.

https://medium.com/@kpatronas/how-to-create-a-bash-script-that-only-executes-from-cron-e50e2f953b5e Page 15 of 15

You might also like