Knowledge / Information Technology / Automation and scripting: Python, Bash and PowerShell

Automation and scripting: Python, Bash and PowerShell

Information Technology (B.E./B.Tech) · Programming · free study notes for exams, placements and interviews

In short

Scripting means writing short interpreted programs that drive the operating system, files, processes and other programs instead of being compiled applications. Python is the general-purpose glue language, Bash the native shell of Linux and Unix servers, and PowerShell the object-oriented shell of Windows and Azure administration. Indian university syllabi examine this as "Scripting Languages", "Shell Programming" or lab work under Operating Systems and Python Programming; GATE CS touches it only through process/file concepts, but placement rounds at TCS, Infosys, Wipro, Cognizant, Accenture, Capgemini, HCLTech and every DevOps or SRE role test it directly. It is the day-one skill for system administration, CI/CD, data cleaning, test automation and RPA.

Explained

What a script is and how it runs

Bash (Linux/Unix shell scripting)

PowerShell (Windows and cross-platform)

Python for automation

Scheduling, triggering and orchestration

Comparison, strengths and limits

Security, compliance and good practice in Indian IT

Key points

Formulas and examples

Exit-status convention: status = 0 (success) or 1-255 (error); $? holds the last status.
cron expression = M H DoM Mon DoW cmd, M 0-59, H 0-23, DoM 1-31, Mon 1-12, DoW 0-6 (0 = Sunday)
Runs per day of */n * * * * = (60/n) × 24, for n dividing 60
Time saved per month (hours) = (manual minutes per run − script minutes per run) × runs per month ÷ 60
Payback (runs) = development time ÷ time saved per run
Permission bits: value = 4(r) + 2(w) + 1(x) per owner/group/other → chmod 750 s.sh

Example 1 - cron frequency and monthly runs. A log-rotation script is scheduled as */20 * * * 1-5.

Example 2 - automation payback in rupees. A junior analyst spends 25 minutes daily consolidating 30 branch CSVs; the Python script does it in 30 s (0.5 min). Development took 6 hours. Loaded cost ₹300/hour.

Example 3 - Bash: disk check with alert.

#!/bin/bash
set -euo pipefail
THRESHOLD=${1:-80}
LOG=/var/log/diskwatch.log
df -hP | awk 'NR>1 {gsub(/%/,"",$5); print $5, $6}' |
while read -r use mount; do
  if [ "$use" -ge "$THRESHOLD" ]; then
    echo "$(date +'%F %T') WARN $mount at ${use}%" | tee -a "$LOG"
  fi
done

Example 4 - PowerShell: top memory consumers to CSV.

Get-Process |
  Where-Object { $_.WorkingSet64 -gt 200MB } |
  Select-Object Name, Id, @{n='MB';e={[math]::Round($_.WorkingSet64/1MB,1)}} |
  Sort-Object MB -Descending |
  Export-Csv -Path .\mem.csv -NoTypeInformation

Example 5 - Python: consolidate CSVs and log.

#!/usr/bin/env python3
import csv, logging, pathlib, sys
logging.basicConfig(filename="merge.log", level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(message)s")
src, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
rows, header = [], None
for f in sorted(src.glob("*.csv")):
    with f.open(newline="", encoding="utf-8") as fh:
        r = csv.reader(fh)
        h = next(r)
        header = header or h
        if h != header:
            logging.error("header mismatch in %s", f.name); sys.exit(2)
        rows.extend(r)
    logging.info("read %s", f.name)
with out.open("w", newline="", encoding="utf-8") as fh:
    w = csv.writer(fh); w.writerow(header); w.writerows(rows)
logging.info("wrote %d rows to %s", len(rows), out)
FeatureBashPowerShellPython
Native platformLinux/Unix, macOS, WSLWindows; 7.x cross-platformAll
Pipeline carriesText (bytes).NET objectsFunction returns / subprocess
Data typesStrings + arraysFull .NET typesRich (list, dict, class)
ArithmeticInteger ($(( )))Full numericFull numeric
Error handlingExit codes, set -e, traptry/catch, error objectstry/except, exceptions
Options parsinggetoptsparam() / [CmdletBinding()]argparse
Best forGluing CLI tools, serversWindows/AD/Azure adminLogic, parsing, APIs, data
Weak atLarge programs, floatsNon-Windows legacy estatesOne-liner shell glue, startup time

Where it is used

Interview questions

Common mistakes

Related topics

Python essentials · Operating systems: processes, files and permissions · Linux system administration · DevOps and CI/CD pipelines · Regular expressions and text processing · Cloud computing and infrastructure as code

Open in the Knowledge reader →Find jobs →