The aim is to create a Bash script that copies all folders and files within a folder to a new location.

The folder name from where the copying should take place should always match the following format:


Folders are located in: /user/members/local/ and should be copied to: /user/members/clean/.

The following scripts have been created, but none of these accomplish the aim.

Script one:

echo $1;

if [[ "$1" =~ [^0-9A-Za-z]+ ]] ; then
echo "string $1 has characters which are not alphanumeric"
echo "string $1 has alphabets which are only alpha numeric"


./test: line 5: conditional binary operator expected
./test: line 5: syntax error near `=~'
./test: line 5: `if [[ "$1" =~ [^0-9A-Za-z]+ ]] ; then'

Script two

if grep '^[-0-9a-zA-Z]*$' <<<$1 ;
  then echo ok;
    else echo ko;


./test 37ee0500-52c0-4a18-861e-0084EF05FB returns ok and ./test 37ee0500-5@c0-4#18-861e-00-0P{9F05FB fails as expected.

Update: This is working;



mv $NEW $OLD;
mkdir $NEW;

cd $OLD;

for f in *; do 

if grep '^[-_.0-9a-zA-Z]*$' <<< "$f" ; 
  then echo $f OK; cp -ar $f $NEW/$f;
     else echo $f Failed;              

  • Can you explain what you tried and what didn't work?
    – grekasius
    Sep 19, 2014 at 16:41
  • @viridis original post updated with example.
    – Rocket
    Sep 19, 2014 at 17:34
  • All files and folders match the same format, i.e. 37ee0500-52c0-4a18-861e-0084EF05FB?
    – 030
    Sep 19, 2014 at 18:05
  • What version of Bash? Those error messages look like a very old version of Bash, such as 2.05b which didn't have =~. Regex matching first appeared in Bash 3 around 2004. Also, in your Bash version, the regex is unanchored so it wouldn't work as you intend. Regexes should be put into variables by habit since some patterns can't be included directly (e.g. those with whitespace). pattern='^[^0-9A-Za-z]+$'; if [[ $1 =~ $pattern ]] Sep 22, 2014 at 16:19

1 Answer 1


If you're on a Linux system with GNU utilities (as opposed to BusyBox or something else), you can do this very efficiently with find and cp:

find /src -maxdepth 1 -type d -regex '.*/[0-9A-Za-z-]+$' -exec cp -r -t /dst {} +

This finds all directories at the top level of /src that contain only alphanumeric characters or hyphens, then passes all of them off to cp to recursively copy them into /dst. The -t option to cp lets you specify the "target directory" first, so all remaining arguments can be the items you want to copy. This allows you to use find's {} + construct, which causes it to pass as many of them as possible to a single cp invocation (similar to xargs). This way, if you have a ton of directories to copy, you aren't invoking cp once for each one.

You must log in to answer this question.

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