Everything you need as a full stack developer

Basic Scripting for Automation (Bash, Python)

- Posted in Junior Developer by

TL;DR Scripting is an essential tool for developers to automate repetitive tasks and optimize workflow, freeing up time to focus on building amazing applications. Bash and Python are two popular languages used for scripting, with Bash being ideal for automating system-level tasks and Python suitable for more complex automation workflows. By leveraging these languages, developers can create scripts that automate tasks such as backing up code repositories, sending emails on application crashes, and more.

Basic Scripting for Automation: A Beginner's Guide to Bash and Python

As a full-stack developer, you're no stranger to the world of automation. Whether it's automating repetitive tasks or streamlining your workflow, scripting is an essential tool in every developer's arsenal. In this article, we'll take a step back and explore the basics of scripting for automation using two popular languages: Bash and Python.

Why Scripting?

Before we dive into the nitty-gritty, let's talk about why scripting is so important. As developers, we're constantly looking for ways to optimize our workflow and reduce the time spent on mundane tasks. Scripting allows us to do just that. By automating repetitive tasks, we can free up more time to focus on the fun stuff – building amazing applications!

Bash Scripting

Let's start with Bash, a Unix shell scripting language that's been around since the 80s. Bash is an excellent choice for automation because it's already installed on most Linux and macOS systems.

Hello World in Bash

Create a new file called hello.sh and add the following code:

#!/bin/bash
echo "Hello, World!"

Let's break this down:

  • The first line, #!/bin/bash, tells the system that this is a Bash script.
  • The second line, echo "Hello, World!", prints the string "Hello, World!" to the console.

To run this script, save the file and make it executable by running chmod +x hello.sh. Then, simply type ./hello.sh in your terminal, and you'll see the familiar "Hello, World!" message.

Automating Tasks with Bash

Bash scripting is all about automating tasks. Let's say we want to create a script that backs up our code repository every day at midnight. We can use Bash to automate this task.

Create a new file called backup.sh and add the following code:

#!/bin/bash
NOW=$(date +"%Y-%m-%d")
tar -czf "backup-$NOW.tar.gz" /path/to/code/repository

Let's break this down:

  • The first line, NOW=$(date +"%Y-%m-%d"), sets a variable NOW to the current date in the format YYYY-MM-DD.
  • The second line, tar -czf "backup-$NOW.tar.gz" /path/to/code/repository, creates a compressed archive of our code repository and saves it with the current date as part of the filename.

To run this script daily at midnight, we can add a cron job. Open your terminal and type crontab -e. Add the following line to schedule the script to run every day at midnight:

0 0 * * * /path/to/backup.sh

Python Scripting

Now that we've covered Bash, let's move on to Python, a popular high-level language that's easy to learn and versatile.

Hello World in Python

Create a new file called hello.py and add the following code:

print("Hello, World!")

Let's break this down:

  • The single line, print("Hello, World!"), prints the string "Hello, World!" to the console.

To run this script, save the file and type python hello.py in your terminal. You'll see the familiar "Hello, World!" message.

Automating Tasks with Python

Python scripting is all about automating tasks. Let's say we want to create a script that sends us an email every time our application crashes. We can use Python to automate this task.

Create a new file called crash_notifier.py and add the following code:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, message):
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = 'your-email@example.com'
    msg['To'] = 'your-email@example.com'

    server = smtplib.SMTP('smtp.example.com')
    server.sendmail('your-email@example.com', 'your-email@example.com', msg.as_string())
    server.quit()

try:
    # your application code here
except Exception as e:
    send_email("Application Crash", str(e))

Let's break this down:

  • The send_email function takes a subject and message as arguments and sends an email using the smtplib library.
  • The try-except block catches any exceptions raised by our application code and calls the send_email function to send us an email with the error message.

Conclusion

In this article, we've covered the basics of scripting for automation using Bash and Python. We've seen how to write simple scripts that print "Hello, World!" and automate tasks like backing up our code repository or sending emails on application crashes.

Scripting is a powerful tool in every developer's arsenal. By automating repetitive tasks, we can free up more time to focus on building amazing applications. Whether you're using Bash or Python, the possibilities are endless.

So, what are you waiting for? Start scripting today and take your automation skills to the next level!

Key Use Case

Here is a workflow/use-case example:

Daily Database Backup: As a developer, I need to ensure that my database is backed up daily to prevent data loss in case of a system failure. I can create a Bash script that automates this task by running a command to dump the database into a compressed archive file with the current date as part of the filename. The script can be scheduled to run daily at midnight using a cron job, ensuring that my database is safely backed up every day without manual intervention.

Finally

As we've seen, scripting allows us to automate repetitive tasks and streamline our workflow. But what if we need to perform more complex tasks or interact with other systems? That's where the true power of scripting comes in – by leveraging the vast array of libraries and tools available for both Bash and Python, we can create sophisticated automation workflows that integrate seamlessly with our existing infrastructure. Whether it's parsing log files, scraping web data, or even machine learning, the possibilities are endless when we combine scripting with other technologies.

Recommended Books

• "Automate the Boring Stuff with Python" by Al Sweigart: A practical guide to automating tasks using Python. • "Linux Shell Scripting with Bash" by Shantanu Tushar: A comprehensive guide to Bash scripting for automation. • "Python Crash Course" by Eric Matthes: A beginner-friendly book that covers the basics of Python programming.

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more