I’m trying to copy files and subfolders from A folder without the A itself. For instance, A folder contains next:
| file1.txt | file2.txt | subfolder1
Executing next command gives me wrong result:
sudo cp -r /home/username/A/ /usr/lib/B/
The result is
/usr/lib/B/A/...copied files...
instead of..
/usr/lib/B/...copied files...
How can I reach the expected one without origin-folder
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
advanced cp
cp -r /home/username/A/. /usr/lib/B/
This is especially great because it works no matter whether the target directory already exists.
shell globbing
If there are not too many objects in the directory then you can use shell globbing:
mkdir -p /usr/lib/B/ shopt -s dotglob cp -r /home/username/A/* /usr/lib/B/
rsync
rsync -a /home/username/A/ /usr/lib/B/
The / at the end of the source path is important; works no matter whether the target directory already exists.
find
mkdir -p /usr/lib/B/
find /home/username/A/ -mindepth 1 -maxdepth 1 -exec cp -r -t /usr/lib/B/ {} +
or if you don’t need empty subdirectories:
find /home/username/A/ -mindepth 1 -type f -exec cp --parents -t /usr/lib/B/ {} +
(without mkdir)
Method 2
If on a GNU system, from man cp:
-T, --no-target-directory
treat DEST as a normal file
This allows you to write cp -rT /home/username/A/ /usr/lib/B/ to do exactly the right thing.
Method 3
Tell cp to copy the directory’s contents and not the directory itself:
sudo cp -r /home/username/A/* /usr/lib/B/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0