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.
The error message syntax error near unexpected token `(' occurs in a Unix-type environment, Cygwin, and in the command-line interface in Windows. This error will most probably be triggered when you try to run a shell script which was edited or created in older DOS/Windows or Mac systems.
That is because parentheses are used for grouping by the shell such that they are not communicated in any way to a command. So, the bash shell will give you a syntax error: $ echo some (parentheses) bash: syntax error near unexpected token `(' $ echo 'some (parentheses)' some (parentheses) Copy link CC BY-SA 3.0.
A parse error: syntax error, unexpected appears when the PHP interpreter detects a missing element. Most of the time, it is caused by a missing curly bracket “}”. To solve this, it will require you to scan the entire file to find the source of the error.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With