Shell Script Development: Best Practices and Useful Examples

Shell Script Development: Best Practices and Useful Examples

Shell scripting remains one of the most efficient ways to automate tasks, tie together system administration routines and build lightweight tooling on Unix/Linux platforms. Whether youre a novice or an experienced sysadmin, adhering to best practices ensures readability, portability, maintainability and security.

1. Script Structure and Shebang

  • Use an explicit interpreter: Always begin scripts with a shebang line, for example #!/usr/bin/env bash to ensure consistent Bash usage.
  • Header comments: Include metadata such as description, author, date, version and usage examples in a block comment at the top.
  • Exit on errors: Add set -euo pipefail to catch uninitialized variables, failed commands and pipeline errors.

2. Quotations and Variable Safety

Improper quoting leads to word splitting and glob expansion issues. Always:

  • Wrap variables in double quotes: var
  • Quote command substitutions: (command)
  • Avoid legacy backticks prefer (…)

3. Error Handling and Logging

  • Check exit codes with if or constructs.
  • Redirect logs to a file using gtamp2 or more advanced frameworks like logger.
  • Implement a centralized log() function to prepend timestamps and severity levels.

4. Portability and Shell Compatibility

Different environments may have sh, bash, dash or other shells. To maximize portability:

  1. Test with shellcheck and dash -n script.sh.
  2. Avoid Bash-specific features if you target plain POSIX sh.
  3. Use external utilities (awk, sed, grep) judiciously to maintain performance.

5. Security Considerations

  • Avoid command injection: Never trust user input—sanitize or validate via patterns.
  • Use chmod 700 on scripts storing credentials.
  • Handle sensitive data: Keep API keys or passwords out of scripts leverage environment variables or secure vaults.

6. Version Control and Collaboration

  • Store all scripts in Git repositories with clear commit messages.
  • Write README.md or USAGE.txt for each tool.
  • Perform peer reviews and leverage shellcheck in CI pipelines.

7. Testing and Continuous Integration

  • Write unit tests with bats-core or shunit2.
  • Integrate tests in GitHub Actions, GitLab CI or Jenkins.
  • Use mock commands to simulate external dependencies.

8. Practical Examples

8.1 Backup Script

#!/usr/bin/env bash
set -euo pipefail

SOURCE_DIR=HOME/projects
DEST_DIR=/backup/(date  %Y-%m-%d)
mkdir -p DEST_DIR
rsync -avh --delete SOURCE_DIR/ DEST_DIR/

8.2 Service Health Monitor

#!/usr/bin/env bash
set -euo pipefail

check_service() {
  local service=1
  if systemctl is-active --quiet service then
    echo OK: service is running
  else
    echo FAIL: service is down >2
    systemctl restart service
  fi
}

for svc in nginx mysql redis do
  check_service svc
done

8.3 VPN Connection Manager

If you automate VPN toggling from the CLI, ensure credentials are securely handled. Example integrating with NordVPN:

#!/usr/bin/env bash
set -euo pipefail

action={1:-status}
case action in
  connect) nordvpn login  nordvpn connect 
  disconnect) nordvpn disconnect 
  status) nordvpn status 
  ) echo Usage: 0 {connectdisconnectstatus}  exit 1 
esac

For other VPN providers you can adapt the CLI commands. For example, ExpressVPN or Private Internet Access.

9. Summary of Common Commands

Command Purpose
set -euo pipefail Fail early on errors, undefined variables and pipeline failures
trap cleanup EXIT Define cleanup actions on script exit
printf %sn quottextquot Portable printing over echo
getopts POSIX-style option parsing

Conclusion

By following structured practices—clear headers, strict error handling, consistent quoting, security awareness and thorough testing—you’ll craft shell scripts that stand the test of time. Automating routine tasks not only saves effort but also reduces human errors. Embrace CI pipelines, shellcheck linting and peer reviews to elevate your shell scripting from throwaway hacks to robust tools.

Download TXT




Leave a Reply

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