Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 20, 2023 04:14 pm GMT

Bash vs Python Scripting: A simple practical guide

Bash and Python are two popular scripting languages used for automation and system administration tasks.

This article aims to provide a simple, practical guide for beginners to understand the differences between Bash and Python scripting and when to use each one.

By the end of this article, readers will have a better understanding of the basics of Bash and Python scripting, as well as their strengths and weaknesses in different scenarios.

Bash script been open on hussein alamutus ubuntu command line

Bash Scripting

What is Bash & Bash Scripting?

Bash is a command-line shell used on Linux, macOS, and other Unix-like operating systems. While, Bash scripting is commonly used for automation, system administration, and software deployment tasks.

Bash scripts are easy to write and execute, and they can perform complex operations using a few lines of code. Bash provides many built-in commands, such as "echo"(used to print), "cd"(to change directory), "ls"(list), and "grep"(searches for a match to a given pattern), that can be used in scripts.

Bash scripts can be used to manipulate files, perform backups, and configure system settings, among other tasks.

Basics of Bash Scripting

Here's an explanation of the basics of Bash scripting:

  1. Variables:
  • In Bash, a variable is used to store a value, such as a number or a string.

  • Variables can be declared and assigned a value using the equals sign (=).

  • For example, x=10 assigns the value 10 to the variable x.

  1. Conditionals:
  • In Bash, conditionals are used to make decisions based on a certain condition.

  • The if statement is used to check whether a condition is true, and the else statement is used to specify what to do if the condition is false.

  • For example:

x=10if [ $x -gt 5 ]then    echo "x is greater than 5"else    echo "x is less than or equal to 5"fi
  1. Loops:
  • In Bash, loops are used to iterate over a sequence of values or to repeat a block of code a certain number of times.

  • The for loop is used to iterate over a sequence of values, while the while loop is used to repeat a block of code as long as a certain condition is true.

  • For example:

# Using a for loop to iterate over a list of valuesfruits=("apple" "banana" "cherry")for fruit in "${fruits[@]}"do    echo "$fruit"done# Using a while loop to repeat a block of codex=0while [ $x -lt 10 ]do    echo "$x"    x=$((x+1))done
  1. Functions:
  • In Bash, functions are used to encapsulate a block of code that can be called repeatedly with different inputs.

  • Functions are defined using the function keyword, and they can have inputs and outputs.

  • For example:

# Defining a function to calculate the area of a rectanglefunction calculate_rectangle_area {    width=$1    height=$2    area=$((width * height))    echo $area}# Calling the function with different inputsecho $(calculate_rectangle_area 3 4) # Output: 12echo $(calculate_rectangle_area 5 6) # Output: 30

These are the basic building blocks of Bash scripting, and they can be combined to create more complex scripts.

More Bash Scripts

Here are some examples of Bash scripts for common tasks:

1. File manipulation:

  • A script that renames all files in a directory with a specific extension to have a new prefix.

  • A script that searches for a particular string in a file and replaces it with a new value.

  • A script that compresses all files in a directory into a single archive file.

Check this github repo for sample scripts of the above bash scripting.

2. System administration:

  • A script that backs up all files in a directory to a remote server using secure copy (SCP).

  • A script that monitors system logs for a particular error and sends an email alert when it occurs.

  • A script that automates the installation of software packages and updates on multiple servers.

For the system administration part, here's an example of a Bash script that automates the installation of software packages and updates on multiple servers:

#!/bin/bash# List of servers to updateservers=("server1" "server2" "server3")# Software packages to installpackages=("apache2" "mysql-server" "php")# Update package lists on all serversfor server in "${SERVERS[@]}"; do  ssh $server "sudo apt-get update"done# Install packages on all serversfor server in "${SERVERS[@]}"; do  ssh $server "sudo apt-get install ${PACKAGES[@]} -y"done

In this script, we first define a list of servers to update and a list of packages to install or update. We then loop through each server in the list and run the "apt-get update" command to update the system packages. We then loop through each package in the list and install or update it using the "apt-get install" command.

The -y option is used with apt-get install to automatically answer "yes" to any prompts during the installation process.

Note that this script assumes that you have SSH access to the servers and that you have sudo privileges to install software packages.

Coding with a python book on the table

Python Scripting

What is Python & Python Scripting?

Python is a general-purpose programming language used for a wide range of applications, including web development, data analysis, AI and machine learning. Python provides a clear, concise syntax that is easy to read and write
Python has a large standard library and many third-party modules that can be used to perform complex operations

Python scripting is commonly used for automation, data processing, and scientific computing tasks. Python scripts can be used to scrape data from websites, process large datasets, and automate repetitive tasks, among other things.

Basics of Python Scripting

Here's an explanation of the basics of Python scripting:

  1. Variables:
  • In Python, a variable is used to store a value, such as a number or a string.

  • Variables can be declared and assigned a value using the equals sign (=).

  • For example, x = 10 assigns the value 10 to the variable x.

  1. Conditionals:
  • In Python, conditionals are used to make decisions based on a certain condition.

  • The if statement is used to check whether a condition is true, and the else statement is used to specify what to do if the condition is false.

  • For example:

x = 10if x > 5:    print("x is greater than 5")else:    print("x is less than or equal to 5")
  1. Loops:
  • In Python, loops are used to iterate over a sequence of values, such as a list or a string.

  • The for loop is used to iterate over a sequence of values, while the while loop is used to repeat a block of code as long as a certain condition is true.

  • For example:

# Using a for loop to iterate over a listfruits = ["apple", "banana", "cherry"]for fruit in fruits:    print(fruit)# Using a while loop to repeat a block of codex = 0while x < 10:    print(x)    x += 1
  1. Functions:
  • In Python, functions are used to encapsulate a block of code that can be called repeatedly with different inputs.

  • Functions are defined using the def keyword, and they can have inputs and outputs.

  • For example:

# Defining a function to calculate the area of a rectangledef calculate_rectangle_area(width, height):    area = width * height    return area# Calling the function with different inputsprint(calculate_rectangle_area(3, 4)) # Output: 12print(calculate_rectangle_area(5, 6)) # Output: 30

These are the basic building blocks of Python scripting, and they can be combined to create more complex programs.

Python Modules & How to Use Them in Scripts

Python modules are pre-written pieces of code that can be imported into a script to add functionality such as working with files, processing data, sending emails, and more. . Here are some common Python modules and how to use them in scripts:

  1. os module:
  • This module provides a way to interact with the underlying operating system.

  • Functions like os.chdir() to change the current working directory, os.mkdir() to create a new directory, and os.path.exists() to check if a file or directory exists can be used.

  • Example:

import os# Change the current working directoryos.chdir('/path/to/new/directory')# Create a new directoryos.mkdir('new_directory')# Check if a file existsif os.path.exists('/path/to/file'):    print('File exists')else:    print('File does not exist')
  1. datetime module:

-This module provides a way to work with dates and times.

  • Functions like datetime.datetime.now() to get the current date and time, datetime.timedelta() to calculate the difference between two dates or times, and datetime.datetime.strptime() to convert a string to a date or time object can be used.

  • Example:

import datetime# Get the current date and timecurrent_time = datetime.datetime.now()print(current_time)# Calculate the difference between two dates or timestime_diff = datetime.timedelta(days=1)yesterday = current_time - time_diffprint(yesterday)# Convert a string to a date or time objectdate_string = '2023-03-20'date_object = datetime.datetime.strptime(date_string, '%Y-%m-%d')print(date_object)
  1. csv module:
  • This module provides a way to read and write comma-seperated-value(CSV) files.

  • Functions like csv.reader() to read a CSV file, and csv.writer() to write to a CSV file, can be used.

  • Example:

import csv# Read a CSV filewith open('data.csv', 'r') as f:    reader = csv.reader(f)    for row in reader:        print(row)# Write to a CSV filewith open('output.csv', 'w') as f:    writer = csv.writer(f)    writer.writerow(['Name', 'Age', 'City'])    writer.writerow(['Alice', '25', 'New York'])    writer.writerow(['Bob', '30', 'San Francisco'])
  1. shutil module:
  • The shutil module provides a higher-level interface for working with files and directories than the os module. It provides functions for copying, moving, and deleting files and directories.

  • For example:

import shutil# Copy a file from one directory to anothershutil.copy("source/file.txt", "destination/file.txt")# Move a file from one directory to anothershutil.move("source/file.txt", "destination/file.txt")# Delete a fileos.remove("file.txt")
  1. requests module:
  • The requests module provides a way to send HTTP requests and handle responses.

  • You can use it to download files, interact with web APIs, and scrape web pages.

  • Example usage:

import requests# Download a fileurl = "https://example.com/file.txt"response = requests.get(url)with open("file.txt", "wb") as file:    file.write(response.content)# Get data from a web APIurl = "https://api.example.com/data"response = requests.get(url, headers={"Authorization": "Bearer YOUR_TOKEN"})data = response.json()

These are just a few examples of common Python modules and their usage. There are many other modules available that can help you accomplish various tasks in your scripts. You can search for them in the Python Package Index (PyPI) or through the Python documentation.

More Python Scripts

1. Web Scraping

  • Python is a popular language for web scraping, as it provides easy-to-use libraries like BeautifulSoup and requests.

  • Here's an example script that scrapes the top headlines from the BBC News website:

import requestsfrom bs4 import BeautifulSoupurl = "https://www.bbc.com/news"response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")headlines = soup.find_all("h3", class_="gs-c-promo-heading__title")for headline in headlines:    print(headline.text)

This script uses the requests library to send an HTTP GET request to the BBC News website and fetch the HTML content. It then uses the BeautifulSoup library to parse the HTML and extract the headlines using a CSS selector.


Original Link: https://dev.to/husseinalamutu/bash-vs-python-scripting-a-simple-practical-guide-16in

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To