I'm not well versed in shell scripting but I imagine this to be a painfully easy fix but its eluding me.

I need to copy the contents of a directory excluding a number of files. I have a command that works when I enter it into the terminal, but when its run in a shell script it fails with a syntax error or just doesn't work.

The command in question is:

cp -r path/to/!(dir1|dir2|dir3) destination

Any help would be greatly appreciated!


That's ksh syntax. bash only recognises that syntax when you enable its extglob option with:

shopt -s extglob

So, you need to add that line to the start of your script, or have it interpreted by ksh instead of bash or call your script with env BASHOPTS=extglob your-script (that latter one not recommended as it would enable the extglob option for every bash shell that your script spawns).

Possibly you have that option enabled in your ~/.bashrc which is why it works at the prompt (~/.bashrc is only read by non-login interactive shells).

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.