Writing Bash Scripts with Python

Loading

Bash scripts are commonly used for automation, system administration, and task scheduling. However, Python can enhance Bash scripts by adding logic, working with APIs, and handling complex data structures. This guide explains how to integrate Python into Bash scripting.


1. Why Use Python in Bash Scripts?

Better Readability: Python code is easier to read and maintain.
Powerful Libraries: Python has libraries for APIs, databases, and data processing.
Cross-Platform Compatibility: Works on Windows, Linux, and macOS.
Automation: Python can automate complex workflows.


2. Running Python in Bash

2.1 Running a Python Script from Bash

If you have a Python script (script.py), you can execute it from Bash like this:

python3 script.py

or

./script.py  # If the script is executable

Make the script executable:

chmod +x script.py

2.2 Using Python Inside a Bash Script

You can call Python within a Bash script:

#!/bin/bash
echo "Running Python Script from Bash"
python3 -c "print('Hello from Python!')"

Save it as script.sh, then run:

bash script.sh

3. Passing Arguments from Bash to Python

3.1 Example: Bash to Python Argument Passing

Bash script (run_python.sh)

#!/bin/bash
name="Narendra"
age=25
python3 script.py "$name" "$age"

Python script (script.py)

import sys

name = sys.argv[1] # First argument
age = sys.argv[2] # Second argument

print(f"Hello {name}, you are {age} years old!")

Run the Bash script:

bash run_python.sh

4. Executing Bash Commands in Python

4.1 Using subprocess Module

Python’s subprocess module allows running shell commands.

import subprocess

# Run ls command
output = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(output.stdout)

4.2 Running Bash Commands and Capturing Output

import subprocess

command = "echo Hello, World!"
output = subprocess.check_output(command, shell=True, text=True)
print("Bash Output:", output)

5. Writing Hybrid Bash-Python Scripts

5.1 Embedding Python in Bash Scripts

Bash allows using Python code inside a script using Here Document (EOF).

#!/bin/bash

echo "Calculating Sum using Python"

sum=$(python3 <<EOF
a = 10
b = 20
print(a + b)
EOF
)

echo "The sum is: $sum"

Run the script:

bash script.sh

6. Automating Tasks with Python and Bash

6.1 Example: Automating File Backup

Bash script (backup.sh)

#!/bin/bash

backup_dir="backup_$(date +%Y%m%d)"
mkdir -p $backup_dir

python3 <<EOF
import shutil
shutil.make_archive("$backup_dir", 'zip', ".")
print("Backup created: $backup_dir.zip")
EOF

Run:

bash backup.sh

7. Scheduling Python Scripts Using Cron Jobs

7.1 Setting Up a Cron Job

Use crontab -e to add a job that runs script.py every day at 5 AM:

0 5 * * * /usr/bin/python3 /path/to/script.py

List scheduled jobs:

crontab -l

Leave a Reply

Your email address will not be published. Required fields are marked *