How to Fix Bad Substitution Error in Bash Scripts
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.
#!/bin/sh var="hello world" echo ${var//o/a}
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.
#!/bin/bash var="hello world" echo ${var//o/a}
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.