cp — copy files and folders
💬 "cp command"
- Concept: A basic Linux command that copies files or folders. It is often the first command used when backing up configuration files or copying deployment files to another path.
- Output behavior: Even on success, it prints nothing to the screen. So you often wonder, "Did it actually copy?"
- Recommended output in practice: If you add the
-voption, it shows the copied result line by line, like'main.go' -> 'main.go.bak'. - Left column: Shows the path or name of the source to copy.
- Right column: Shows the path or name of the newly created copy.
Three essential command combinations
cp file1 file2— copy one file under a different namecp -r folder1 folder2— copy a folder and all of its contentscp -a source target— copy while preserving permissions, owner, and timestamps (for backups)
It is also good to remember two more options that help prevent mistakes.
-i— asks before overwriting.-n— skips without overwriting if the file already exists.
💬 "Show me one way to apply this"
Scenario: Before touching a working nginx configuration, back it up safely with a date appended.
Step 1: Check the original file
First, check whether the file to back up exists and how large it is.
ls -l nginx.conf
Step 2: Back up with a date appended
Use -a to preserve permissions and timestamps, and save a backup with today's date appended to the file name.
cp -a nginx.conf nginx.conf.$(date +%F).bak
Step 3: Verify the result
Compare the size and permissions of the original and the backup. If you also use -v, you can log the copy process.
ls -l nginx.conf*
cp -v nginx.conf nginx.conf.$(date +%F).bak
Actual execution screen
This is an example of copying a file with cp -v. The source being copied and the newly created copy are shown with an arrow.
!cp -v output: copying main.go to main.go.bak
Actual production server
Source (HTML): https://games.aidebatehub.com/programs/linux/filesystem/cp.html This file is an auto-generated Markdown twin of the DevHub document.
AI Knowledge Hub
Visitor Comments