I need to run this command in a shell script to copy source > destination and exclude a folder.

No rsync, tar, find, mv, etc.

Exactly this command:

cp -var test/!(test2) testbkp

  1. In the shell it works
  2. Run from a Bash script without exclude like cp -var test testbkp it works.

When I try to run from a Bash script with the exclude option

cp -var test/!(test2) testbkp, it doesn't work.

There isn't any output, nothing, and no error message.

I checked this post too, but no result: cp command won't run if executed from shell script

How can I run this cp command in a Bash script and exclude folders?

  • 2
    cp is not part of bash -- it's a separate executable (typically something like /usr/bin/cp) you can use without any shell at all; so "bash 'cp' command" is somewhat misleading. On the other hand, it is the shell responsible for taking a glob expression (like test/!(test2)) and generating a list of filenames from that expression before the cp executable (or whatever other executable you run) is started. Mar 10, 2023 at 16:44

1 Answer 1


You should enable the extglob option, it isn't enabled by default in scripts:

shopt -s extglob
cp -var test/!(test2) testbkp

Also verify that the script is indeed running under bash.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .