Skip to content
Advertisement

Error “syntax error near unexpected token ‘(‘” in Bash script when selecting files

Running this script, bash ./cleanup.bash,

#!/bin/bash
## Going to directory-moving stuff
rm -rf !(composer.json|.git)

Gives the error:

cleanup.bash: line 10: syntax error near unexpected token ‘(‘ cleanup.bash: line 10: ‘rm -rf !(composer.json|.git)’

But if I run in in the terminal directly, there aren’t any problems:

rm -rf !(composer.json|.git)

I tried stripping out all other lines, but I still get the error.

How do I enter this correctly in the Bash script?

I’m on Ubuntu, and this was all done locally, not on a remote.

Advertisement

Answer

I guess your problem is due to the shell extended glob option not set when run from the script. When you claim it works in the command line, you have somehow set the extglob flag which allow to !() globs.

Since the Bash script, whenever started with a #!/bin/bash, starts a new sub-shell, the extended options set in the parent shell may not be reflected in the new shell. To make it take effect, set it in the script after the shebang:

#!/bin/bash

shopt -s extglob

## Going to directory-moving stuff
rm -rf !(composer.json|.git)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement