Creating a Custom Bash Script in Python Using subprocess

Bash scripts are widely used for automating tasks in Linux, but sometimes Python is a better choice for handling complex logic. With Python’s subprocess module, you can execute Bash commands, integrate system operations, and even create custom Bash-like scripts.

Why Use Python for Bash Scripting?

  • Easier to manage logic and error handling
  • More readable than pure Bash scripts
  • Ability to leverage Python libraries
  • Cross-platform compatibility

Using subprocess to Run Bash Commands

The subprocess module allows executing system commands just like a Bash script.

Running a Simple Command

result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)

This runs the ls -l command and prints the output.

Running a Command with Piping

result = subprocess.run("ls -l | grep py", shell=True, capture_output=True, text=True)
print(result.stdout)

Using shell=True allows executing compound commands like piping.

Creating a Custom Bash Script in Python

Here’s a script that automates system tasks using Python.

import subprocess

def check_disk_space():
    subprocess.run(["df", "-h"])

def list_files(directory="."):
    subprocess.run(["ls", "-l", directory])

def main():
    print("1. Check Disk Space")
    print("2. List Files")
    choice = input("Choose an option: ")
    if choice == "1":
        check_disk_space()
    elif choice == "2":
        dir_path = input("Enter directory path: ")
        list_files(dir_path)
    else:
        print("Invalid choice")

if __name__ == "__main__":
    main()

Making the Script Executable

Save this as script.py, then make it executable:

chmod +x script.py
./script.py

Conclusion

Python can serve as an effective alternative to Bash scripting by using the subprocess module. This approach provides better flexibility, debugging capabilities, and integration with other Python tools.

Leave a Comment

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

Scroll to Top