Copying contents of current directory to a subdirectory
Solution 1
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
Solution 2
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/
.
Solution 3
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.
Related videos on Youtube
Oguz Bilgic
Updated on September 17, 2022Comments
-
Oguz Bilgic over 1 year
How can I use the Linux terminal to copy everything in current directory to a subdirectory?
-
Craig over 13 yearsDo you mean copy or move?
-
-
Admin over 13 yearsthis does not take care of non-empty directories
-
karlphillip over 13 yearsI just tested, and it worked.
-
Admin over 13 yearsthis does not work in case sub/ is not empty -> sub will copied into sub again, unless that is what @Oguz wanted.
-
Admin over 13 yearsyou need to copy the non-empty directories recursively like @Lekensteyn suggested.
-
Lekensteyn over 13 yearsOk I'm finally satisfied with the
find
code :D -
Dennis Williamson over 13 yearsFails for filenames that include spaces.
-
Dennis Williamson over 13 yearsNo need for
ls
:for file in *
. No need for backticks - use$()
. No need for backticks (or$()
) around thecp
command (that will produce an error message). -
Dennis Williamson over 13 yearsYour second command fails for filenames that include spaces. Use
xargs
or-exec
. No need forgrep
- use! -name "$TARGETDIR"
or similar. You have unmatched quotes around$file
. I don't think a recursivecp
will work the way you intend in any but your first command. -
Lekensteyn over 13 yearsWohaa, missed a quote in the last codes. Good comment Dennis, I never thought of using -name in this case :)
-
Jimmy Obonyo Abor about 3 yearswill throw error
cp: cannot copy a directory, 'a', into itself, 'a/a'