I assume your problem is that the extended shell extension option is not set when running from a script. When you claim that it works on the command line, you somehow set the extglob flag, which allows !() Globs.
Since a bash script whenever it starts with #!/bin/bash starts a new sub-shell, the advanced options set in the parent shell may not appear in the new shell. To make it effect, set it to script after it-bang
#!/bin/bash shopt -s extglob
Inian source share