Parenthesis works in bash shell itself, but not in bash script
That's because the syntax you're using depends on a particular bash feature which is not activated by default for non-interactive shells (scripts). You can activate it by adding the relevant command to your script:
## Enable extended globbing features
shopt -s extglob
if [ -d "folder" ]; then
cp -r folder/!(exclude-me) ./
rm -rf folder
fi
This is the relevant section of man bash
:
If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized. In the following
description, a pattern-list is a list of one or more patterns separated
by a |. Composite patterns may be formed using one or more of the fol‐
lowing sub-patterns:
?(pattern-list)
Matches zero or one occurrence of the given patterns
*(pattern-list)
Matches zero or more occurrences of the given patterns
+(pattern-list)
Matches one or more occurrences of the given patterns
@(pattern-list)
Matches one of the given patterns
!(pattern-list)
Matches anything except one of the given patterns
Add this line near top of your script:
shopt -s extglob
!(...)
is an extended pattern matching feature, you need extglob
option enable to use it. See shopt builtin for more details.