# Minimal S.

Bad substitution error using bash or zsh

If you are a M1 Mac user or higher and trying to use bash scripts on your project for creating files or automation, you may want to convert your variables to lowercase or uppercase letters. This may be the reason why you're encountering the "bad substitution" error. At the top of your script, you may have included bash instead of zsh. You may have assumed that the default shell was bash or that the zsh commands are similar enough to bash that they are compatible. However, this is not the case, and using the wrong syntax can result in the "bad substitution" error.

Example:

#!/bin/bash
 
#input variable
read -p "enter name" var
 
#create content for file
content=$(cat << EOF
function {$var,,}(){
  //content
}
export $var
EOF ) #bad substitution
 
# add content to file
echo content > "./filepath/example.tsx"

The above code will not work. In your terminal, you will see a bad substitution error, and your files will not be created in the path you specified. This error can be frustrating and difficult to understand, especially because the error is reconigized on the last time of the concatenating.

What causes the "bad substitution" error?

The "bad substitution" error is typically caused by using the wrong syntax, for this particular instance the lowercase expansion in ZSH. In Bash, you can use the ${VAR,,} syntax to lowercase a variable. However, this syntax is not supported in ZSH.

Instead, ZSH uses the ${VAR:l} syntax to lowercase a variable. This syntax applies the l flag to the VAR variable, which stands for "lowercase".

If you try to use the Bash syntax in ZSH, you'll get a "bad substitution" error because the shell doesn't recognize the ,, part of the expansion.

How to fix the "bad substitution" error

To fix the "bad substitution" error in ZSH, you'll need to use the correct syntax for lowercase expansion. Simply replace the ${VAR,,} syntax with ${VAR:l}, and the error should disappear.

Here's an example of how to use the correct syntax in ZSH:

 
VAR="HELLO WORLD"
echo {$VAR:l} #outputs "hello world"

or using the example from above:

#!/bin/zsh
 
#input variable
read -p "enter name" var
 
#create content for file
content=$(cat << EOF
function {$var:l}(){
  //content
}
export $var
EOF ) #bad substitution
 
# add content to file
echo content > "./filepath/example.tsx"

That's all there is to it! With this simple change, you can use lowercase expansion in ZSH without encountering any errors.

It's worth noting that the ${VAR:l} syntax is not only limited to lowercase expansion. You can also use it to perform other string manipulations, such as uppercase expansion ${VAR:u}, capitalization ${VAR:c}, and more.