Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy all of the files from one directory to another in a bash script [closed]

Tags:

linux

bash

I want to copy all of the files from a subdirectory into another directory without copying the original folder. In a terminal I would just do this:

cp -r dir1/* dir2

and then dir2 will contain all of the files from dir1 without containing dir1 itself. I am trying to replicate this in a bash script and I am getting an error. Here is my bash code:

cp -r $pck_dir"/*" $TAR_DIR"/pck/"

I get this error:

cp: cannot stat ‘./mailman/lists/mailman/*’: No such file or directory

This is strange because I can verify that the directory in question exists. I believe bash is complaining about the '*' but I am not sure why. Can someone enlighten me as to what I am doing wrong?

like image 702
user3361761 Avatar asked May 16 '14 06:05

user3361761


People also ask

How do I copy files from one directory to another in bash?

Copy a Directory and Its Contents ( cp -r ) Similarly, you can copy an entire directory to another directory using cp -r followed by the directory name that you want to copy and the name of the directory to where you want to copy the directory (e.g. cp -r directory-name-1 directory-name-2 ).

How do I copy multiple files from one directory to another in Linux?

To copy multiple files you can use wildcards (cp *. extension) having same pattern. Syntax: cp *.

How do I copy a file from one directory to another in Linux?

You can copy files by right-clicking on the file and selecting "Copy", then going to a different directory and selecting "Paste". For my terminal friends, you can also perform file copy-paste operations without leaving the terminal. In a Linux-based terminal, you do this using the cp command.

How do you copy all files in a directory to another directory in Ubuntu?

To copy multiple files with the “cp” command, navigate the terminal to the directory where files are saved and then run the “cp” command with the file names you want to copy and the destination path.


1 Answers

Expanding on devnull's comment:

  • Quotes of any kind around a wildcard, like *, will prevent the shell from expanding the wildcard. Thus, you should only write "/*" if you want a slash followed by a literal star.

  • An unquoted variable will be subject to word splitting. So, if pck_dir had the value my dir, then $pck_dir"/*" would be expanded to two words my and dir/* and both words would be passed to cp as separate arguments. Unless you want word splitting, shell variables should always be in double quotes.

Thus, to get what you want, use:

cp -r "$pck_dir"/* "$TAR_DIR/pck/"
like image 195
John1024 Avatar answered Sep 18 '22 08:09

John1024