This guide walks you through writing automation scripts in Python, Bash, and PowerShell. You’ll learn the core patterns for each language, how to structure a script, and how to handle common tasks like file operations, loops, and error handling. By the end, you’ll be able to automate repetitive tasks on Windows, macOS, or Linux.
What You’ll Need
- A computer with a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS/Linux).
- Python installed (version 3.6 or newer). Check with
python --versionorpython3 --version. - Basic familiarity with text editing and command-line navigation.
- For PowerShell, any Windows 10/11 or PowerShell 7+ installation.
Step-by-Step
- Define your automation goal. Write down exactly what you want to automate. For example, “rename all files in a folder to add a date prefix” or “check if a website is down and send an alert.” Break it into smaller steps: list files, modify names, verify results.
- Start with a simple script in your chosen language. For Bash, create a file ending in
.sh. For Python, use.py. For PowerShell, use.ps1. Begin with a “hello world” to test the environment. - Learn the basic syntax. In Bash,
echo "Hello"prints text. In Python,print("Hello"). In PowerShell,Write-Host "Hello"orWrite-Output. - Use variables to store data. Bash:
name="World"; echo "Hello $name". Python:name = "World"; print(f"Hello {name}"). PowerShell:$name = "World"; Write-Host "Hello $name". - Add logic with conditionals. If a file exists, do something. Bash:
if [ -f "file.txt" ]; then echo "Found"; fi. Python:import os; if os.path.exists("file.txt"): print("Found"). PowerShell:if (Test-Path "file.txt") { Write-Host "Found" }. - Loop through items. For files in a folder, process each. Bash:
for f in *.txt; do echo "$f"; done. Python:import glob; for f in glob.glob('*.txt'): print(f). PowerShell:Get-ChildItem *.txt | ForEach-Object { Write-Host $_.Name }. - Handle errors gracefully. Bash: use
set -eto exit on error, or check exit codes. Python: usetry/except. PowerShell: usetry/catch. - Test your script with sample data. Run it on a copy of your real data to ensure it works as expected.
- Make the script executable (Bash only). Run
chmod +x script.shto allow execution. - Schedule the script. On Linux/macOS, use
cron(e.g.,crontab -eand add0 2 * * * /path/to/script.sh). On Windows, use Task Scheduler to run a PowerShell script at a set time.
Common Mistakes
- Not using absolute paths. Scripts often run from different directories. Use full paths or make the script change to its own directory first.
- Hardcoding values. Avoid embedding file names or numbers directly; use variables or arguments instead.
- Forgetting about permissions. On Linux/macOS, scripts need execute permission. On Windows, PowerShell execution policy may block scripts; use
Set-ExecutionPolicy RemoteSignedfor local scripts. - Ignoring error output. Always check stderr or exception messages. Redirect output to a log file for debugging.
- Mixing line endings. Windows uses CRLF, Unix uses LF. If you edit a script on Windows and run it on Linux, you may get errors. Use a text editor that handles this or run
dos2unix.
Tips
- Start small. Automate one tiny task first, then build up.
- Use comments. Explain why you wrote something, not just what it does.
- Make scripts idempotent. Running them multiple times should not cause problems (e.g., don’t duplicate files).
- Use command-line arguments. This makes scripts reusable. In Python, use
sys.argvorargparse. In Bash, use$1,$2. In PowerShell, useparam(). - Log your actions. Write a timestamped log file to see what happened.
- Test in a sandbox. Use a test folder before running on production data.
Troubleshooting
- Script won’t run. Check permissions (Bash), execution policy (PowerShell), or Python path. Try running with
bash script.shorpython script.pydirectly. - Unexpected output. Add debug prints or use
set -xin Bash,print()in Python, orWrite-Debugin PowerShell to trace execution. - File not found. Verify the path is correct. Use
pwdto see current directory. In Python, useos.path.abspath(). - Syntax errors. Check for missing quotes, parentheses, or semicolons. Use a linter or IDE with syntax highlighting.
- Script works manually but not when scheduled. The scheduled environment may have different environment variables or working directory. Set absolute paths and ensure the interpreter is fully qualified (e.g.,
/usr/bin/python3).
Frequently Asked Questions
Can I run the same script on Windows and Linux?
Not directly. Bash scripts run on Linux/macOS, PowerShell on Windows, and Python anywhere with Python installed. To make a cross-platform script, use Python, which works on all three.
How do I pass arguments to a script?
In Bash, use $1, $2 etc. In Python, use sys.argv (e.g., sys.argv[1]). In PowerShell, define param([string]$arg1) at the top.
What’s the best language for beginners?
Python is often recommended because of its readable syntax and huge library support. Bash is great for simple file operations on Unix-like systems, and PowerShell is powerful on Windows.
How do I schedule a Python script on Windows?
Use Task Scheduler: create a basic task, set the trigger (e.g., daily), and in the action set the program to python.exe and add your script path as an argument.
Is it safe to delete files with a script?
Only if you’re absolutely sure. Always test with a dry run (e.g., print the file names instead of deleting) and consider moving files to a trash folder instead of permanent deletion.
How do I make a script run at startup?
On Linux, add a line to crontab with @reboot. On Windows, place a shortcut in the Startup folder or use Task Scheduler with the trigger “At startup”.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Gmail Gemini Privacy: Data Access & Limit Settings
- Fix Outlook Inbox Corruption with DISM in Windows
- How to Set Up Apple Pay on iPhone
- How to Choose a Refurbished iPhone With Years of Support
- Voice Dictation in Google Docs: How to Use It
- Turn Off Message Notifications on Mac