3

I have two existing directories :

  • foo: directory with dotfiles in it
  • foo2: empty directory

I would like to have a solution to copy all dotfiles in foo to foo2. I would like a solution that is not shell-dependent (bash, zsh, etc.). I would prefer not having to install rsync to do it (tar is ok).

Weeks ago, I asked this similar question, but I feel both questions should be separated as they answer different needs. All answers were shell-dependent or using rsync.

Gradient
  • 3,659
  • 2
    What's wrong with cp -r foo/.??* foo2/? – Joseph R. Sep 15 '13 at 21:46
  • Beat me to it Joseph, was going to say the same. Dropping the -r option will only copy files as directories will give the cp: omitting directory error. – Drav Sloan Sep 15 '13 at 21:48
  • @JosephR. Why do you add ??? – Gradient Sep 15 '13 at 22:07
  • @Gradient To ensure the files/directories that match have at least 3 characters so you avoid matching . and .. which would be... unpleasant. – Joseph R. Sep 15 '13 at 22:13
  • @JosephR. Is it standard on all shells? – Gradient Sep 15 '13 at 22:14
  • @Gradient: here is a portable solution, avoiding duplicates (as in chosen answer) : for i in foo/.* ; do [ "$i" = "foo/." ] && continue ; [ "$i" = "foo/.." ] && continue ; cp -r "$i" foo2 ; done (ie, list all .* and avoid "." and ".." only). It does copy file and/or directories as well. If you want only files, replace it by: for i in foo/.* ; do [ ! -f "$i" ] && { echo "skipping: $i" ; continue ; } ; cp -r "$i" foo2 ; done – Olivier Dulac Oct 02 '13 at 18:10

2 Answers2

3

If you want to copy everything, including dotfiles:

cp -a src/. dest
1

I assume by "shell independent", you are restricting yourself to Bourne-type shells (not csh, etc)

cp -r foo/.??* foo/.[^.] foo2
glenn jackman
  • 85,964
  • 3
    Note that it is not shell independant since [^.] is not Bourne nor POSIX (though is csh, [!.] is the POSIX one). Also, -r is not portable. Also in zsh, if either of those patterns doesn't match any file, an error will be reported and the command will not be run. Also a file called .[^.] may be copied twice. – Stéphane Chazelas Sep 16 '13 at 11:00