11

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.

10
  • check previous lines also Commented Nov 15, 2017 at 10:01
  • nope, even when it's the only line in the file. it gives this error. Commented Nov 15, 2017 at 10:03
  • try doing set -o posix or set +o posix before rm command. Commented Nov 15, 2017 at 10:04
  • 1
    @Inian that gives a new error line 9: set: -s: invalid option Commented Nov 15, 2017 at 10:34
  • 1
    @janw: I meant it to be shopt -s extglob Commented Nov 15, 2017 at 10:37

1 Answer 1

12

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)
Sign up to request clarification or add additional context in comments.

2 Comments

yep this is it :)
Important to run this outside of any "scope" of the script (ex. for loop, if block, etc). If you run shopt -s extglob only inside an 'if' block, it won't be in effect there. Running it after the she-bang as this answer states avoids the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.