0
0
Bash-scriptingDebug / FixBeginner · 3 min read

How to Fix Bad Substitution Error in Bash Scripts

The bad substitution error in bash happens when you use parameter expansion syntax not supported by your shell, often because the script runs in sh instead of bash. To fix it, ensure your script uses bash by starting with #!/bin/bash and use correct bash parameter expansion syntax.
🔍

Why This Happens

This error occurs because the shell running your script does not understand the parameter expansion syntax you used. For example, ${var//pattern/replacement} is a bash-specific feature. If your script runs with sh or a shell that does not support this, it will show bad substitution.

bash
#!/bin/sh
var="hello world"
echo ${var//o/a}
Output
bad substitution
🔧

The Fix

Change the script to run with bash by using #!/bin/bash at the top. This ensures the shell understands bash-specific syntax. Alternatively, avoid bash-only expansions or rewrite them in POSIX-compatible ways.

bash
#!/bin/bash
var="hello world"
echo ${var//o/a}
Output
hella warld
🛡️

Prevention

Always specify #!/bin/bash if you use bash features. Run scripts explicitly with bash script.sh instead of sh script.sh. Use shellcheck tool to catch unsupported syntax early. Write POSIX-compatible code if you want portability.

⚠️

Related Errors

Other common errors include command not found when using bash-only commands in sh, or syntax errors from using arrays in shells that don't support them. Fixes usually involve using the correct shell or rewriting code.

Key Takeaways

Use #!/bin/bash to run scripts with bash and avoid bad substitution errors.
Avoid bash-specific syntax if your script must run in sh or other shells.
Run scripts explicitly with bash: bash script.sh instead of sh script.sh.
Use shellcheck to detect unsupported syntax before running scripts.
Rewrite parameter expansions to POSIX style for maximum compatibility.