Least privilege shell scripting exists to stop that from happening. It means running every script with the minimum permissions needed to do its job—no more, no less. You write code that cannot harm what it was never meant to touch. You remove attack surfaces, limit lateral movement, and shrink the blast radius of mistakes or breaches.
Start by defining the exact resources your script needs. If it only reads logs, it should not have write rights. If it manipulates a database table, it should not have root access. Create dedicated system users or groups just for that script, and assign the narrowest permissions possible. Use chmod and chown to lock files and directories. Avoid running shell scripts as root unless absolutely unavoidable.
Break complex tasks into smaller scripts, each with their own scope and permissions. This containment ensures that a compromise in one area does not cascade across the system. When invoking other commands or binaries, use full paths and whitelist what’s allowed. Avoid relying on global environment variables that could be hijacked.