0
0
Bash Scriptingscripting~5 mins

Script security best practices in Bash Scripting

Choose your learning style9 modes available
Introduction

Keeping scripts safe stops bad things from happening to your computer or data. It helps protect your work and privacy.

When writing scripts that handle passwords or secret keys
When sharing scripts with others or running scripts from the internet
When automating tasks that change important files or system settings
When running scripts on a server or multi-user computer
When your script uses input from users or other programs
Syntax
Bash Scripting
# Example of safe script practices
# 1. Use strict mode
set -euo pipefail

# 2. Check inputs
if [[ $# -eq 0 ]]; then
  echo "Error: Missing argument" >&2
  exit 1
fi

# 3. Avoid running commands as root unless needed

# 4. Use full paths for commands
/usr/bin/grep "pattern" file.txt

# 5. Do not store passwords in plain text

set -euo pipefail helps catch errors early and avoid unexpected behavior.

Always check inputs to avoid running dangerous commands by mistake.

Examples
This is called 'strict mode' and makes your script safer by stopping on errors.
Bash Scripting
set -euo pipefail

# This stops the script if any command fails, if you use an unset variable, or if a pipeline fails.
This checks if no argument is provided and stops the script with an error message.
Bash Scripting
if [[ $# -eq 0 ]]; then
  echo "Error: Missing argument" >&2
  exit 1
fi
Using full paths avoids running the wrong program if someone changes your PATH.
Bash Scripting
/usr/bin/grep "pattern" file.txt
Storing passwords in scripts can expose them to others.
Bash Scripting
# Never store passwords like this:
PASSWORD="mypassword"
# Instead, read from secure input or environment variables.
Sample Program

This script safely checks for a filename argument, verifies the file can be read, and searches for the word 'root' using the full path to grep.

Bash Scripting
#!/bin/bash
set -euo pipefail

# Check if user provided a filename
if [[ $# -eq 0 ]]; then
  echo "Usage: $0 filename" >&2
  exit 1
fi

FILE="$1"

# Check if file exists and is readable
if [[ ! -r "$FILE" ]]; then
  echo "Error: File '$FILE' does not exist or is not readable." >&2
  exit 1
fi

# Use full path for grep
/usr/bin/grep "root" "$FILE" || echo "No 'root' found in $FILE"
OutputSuccess
Important Notes

Always run scripts with the least privileges needed.

Never trust user input without checking it first.

Keep sensitive data out of scripts or use secure storage methods.

Summary

Use strict mode (set -euo pipefail) to catch errors early.

Check all inputs before using them in your script.

Use full paths for commands and avoid storing secrets in plain text.