I read that I must put the command

shopt -s extglob

in .bashrc in order to use !(XYZ) as a wild card expansion for everything in the current directory except XYZ. Testing indicated that

cp -aruv !(XYZ) $target

indeed copied everything from the current directory to $target except sub directory XYZ. Then I included the cp statement in a bash script. The script died at the cp statement with error message

cp: invalid option --'h'

which I cannot explain. I added the shopt command to my script and got the same result.

I found this wild card expansion in "Your UNIX" by Das with the comment to add the shopt statement to .bashrc. I do not find shopt in either man or info.

Any help would be appreciated to get the correct wild card expansion in a bash script statement and on where to find information on the shopt command.

There have been questions about my script that I tried to answer but did so in the wrong place. There are portions of the script.

if shopt -s extglob
    echo "shopt was successful"
    echo "shopt was not successful"
    exit -1

Following these statements is a loop in which target and source are set and tested to insure that they point to directories. Then the code that fails

cd $source
cp -aruv !(XYZ) $target 

Again I point out that if I set target and source from the command line and then

cd $source
cp -aruv !(XYZ) $target

the copy works as I expect. I can do this other ways but would like to understand why this does not work in my script and how to fix it.

  • 3
    So where is the script you speak of? – George Udosen Jul 12 '18 at 18:25
  • This would occur in the (unlikely) event that your directory contains a file called '-h'. – zwets Jul 12 '18 at 20:01
  • Please include the relevant lines from your script. We can't help you much without them. You'll find shopt under help since it is a shell builtin (help shopt). – Seth Jul 12 '18 at 21:20
  • ...and the first line is relevant too, you may be even be running bash. e.g. #!/bin/sh is really running dash. – ubfan1 Jul 12 '18 at 21:26
  • My script is listed with line numbers. – Mack Elrod Jul 12 '18 at 22:56

If you are using the default Ubuntu ~/.bashrc file, then extended globbing is enabled by default1 for interactive shells - which is why it works on the command line.

Inside a script however, you will need to enable it with

shopt -s extglob

shopt is documented in man bash under the SHELL BUILTIN COMMANDS section, or via the shell's online help

help shopt

1 albeit rather opaquely, via bash completions. See for example Where is bash's “shopt extglob” turned on for my interactive shell?

| improve this answer | |
  • I put the shopt comaand as the second line of my script. The same error occurs. – Mack Elrod Jul 12 '18 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.