Copying contents of current directory to a subdirectory

How can I use the Linux terminal to copy everything in current directory to a subdirectory?

1

6 Answers

If you want to copy the contents of the folder recursively (will throw 1 error, alternatives below):

cp -r * sub/

A little more hacky, but works on non-empty subdirectories:

TARGETDIR='targetdir here';cp -r `find . -maxdepth 1 ! -name "$TARGETDIR"` "$TARGETDIR"

Another oneliner:

TARGETDIR='targetdir here';for file in *;do test "$file" != "$TARGETDIR" && cp "$file" "$TARGETDIR/";done

Or recursive:

TARGETDIR='z';for file in *;do test "$file" != "$TARGETDIR" && cp -r "$file" "$TARGETDIR/";done
4

Supposing target is the name of the target subdirectory, if your shell is bash:

shopt -s extglob
cp -r !(target) target/

In ksh, you can directly do cp -r !(target) target/.

In zsh, you can do setopt ksh_glob then cp -r !(target) target/. Another possibility is setopt extended_glob then cp -r ^target target/.

I would suggest moving the target directory outside the source directory and then put it back again; mv is free (if you are careful not to move to a different filesystem), unless you are expecting other processes to interfere/be interfered.

Most solutions posted above won't work if there are spaces in filenames. I would suggest using variants of find -print0 | xargs -0, or find -exec, etc.

Will this work for you?

cp -r * subdir/

If you meant to move instead of copying everything in the current dir to a subdirectory, you could do:

mv * subdir/
4

This will copy everything, including dot files, and not including the target directory itself, to the target directory SUBDIR:

for i in `ls -a | grep -Ev '^(SUBDIR|\.\.?)$'`; do cp $i SUBDIR; done
1

This goes in say file dirCopy.sh

for i in `ls`
do if [ $i != "subDir" ] then `cp -r $i subDir` fi
done

run it as " sh dirCopy.sh " in your console

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like