Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 746
janw Avatar asked Nov 15 '17 09:11

janw


People also ask

What Is syntax error near unexpected token?

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.

What is syntax error in bash?

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.

What does syntax error unexpected?

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.


1 Answers

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)
like image 176
Inian Avatar answered Nov 10 '22 23:11

Inian