Przejdลบ do treล›ci

๐Ÿง  Bash

Bash (Bourne Again Shell) is the most widely used generalโ€‘purpose shell on Linux systems. It combines POSIX sh compatibility with many powerful extensions, making it suitable for both scripting and interactive use.


๐ŸŽ“ Who This Is For

  • Developers writing internal tooling and automation
  • DevOps/SRE engineers maintaining scripts on Linux systems
  • Users migrating legacy bash scripts to more portable forms
  • Anyone who needs to understand when bash is appropriate vs POSIX sh

๐Ÿงฉ Role in the Ecosystem

  • Default interactive shell on many Linux distributions (though less so recently)
  • Commonly assumed in tutorials, blog posts, and legacy scripts
  • Often used as /bin/bash explicitly in scripts that rely on extensions
  • Not guaranteed to be available as /bin/sh or on minimal/container images

๐Ÿงฉ Key Characteristics

  • Superset of POSIX sh (but not strictly POSIX by default)
  • Supports arrays, associative arrays, [[ ... ]], process substitution, brace expansion
  • Rich interactive features (history, completion, readline)
  • Large ecosystem of scripts and tooling

๐Ÿ”ง Notable Features

  • Arrays:
1
2
arr=(one two three)
echo "${arr[1]}"
  • [[ ... ]] test syntax:
1
2
3
if [[ $var == foo* ]]; then
  ...
fi
  • Process substitution:
1
diff <(sort a) <(sort b)
  • Brace expansion:
1
echo file_{1..3}.log

โš ๏ธ Limitations & Pitfalls

  • Not available by default on all systems (e.g., some minimal containers, embedded systems, older Unix)
  • Scripts using bashโ€‘specific features are not portable to /bin/sh
  • Some bashisms silently break when run under dash, ash, or BusyBox sh
  • Interactive configuration (.bashrc) is not loaded in nonโ€‘interactive scripts

๐Ÿง  When to Use Bash

  • Internal tooling where you control the environment
  • Developer machines with guaranteed /bin/bash
  • Scripts that benefit from arrays, [[ ]], or process substitution
  • Prototyping complex shell logic before rewriting in another language

โœ… Best Practices

  • Use #!/usr/bin/env bash when you truly require bash
  • Document that a script requires bash, not just โ€œshโ€
  • Avoid bashisms in scripts intended for /bin/sh or CI/CD runners
  • Prefer POSIX syntax when portability matters
  • Test scripts under bash --posix if you aim for POSIX compatibility

๐Ÿงช Testing Bash Scripts

1
2
3
bash -n script.sh        # syntax check
bash -u script.sh        # treat unset vars as errors
bash -x script.sh        # trace execution

๐Ÿง  Summary

Bash is powerful and convenient, but not universal. Use it deliberately where its features are needed, and fall back to POSIX sh when portability and minimalism are more important.