BudiBadu Logo
Samplebadu

Bash by Example: Copy Files

Bash 5.0+

Duplicating files and directories using the cp command with various preservation options, understanding the difference between copying single files and recursive directory copies with -r, preserving file attributes like timestamps and permissions with -p, implementing backup strategies, and handling symbolic links properly.

Code

#!/bin/bash

# Setup
echo "Original" > original.txt
mkdir -p backup

# 1. Copy single file
cp original.txt copy.txt
echo "Copied to copy.txt"

# 2. Copy to a directory
cp original.txt backup/
echo "Copied to backup/"

# 3. Copy with rename
cp original.txt backup/renamed.txt

# 4. Recursive copy (for directories)
mkdir -p source_dir/sub
touch source_dir/file.data
cp -r source_dir backup_dir
echo "Copied directory recursively"

# 5. Preserve attributes (archive mode)
cp -a original.txt preserved.txt

rm original.txt copy.txt preserved.txt
rm -rf backup source_dir backup_dir

Explanation

The cp command copies files or directories. The basic syntax is cp source destination.

Key flags:

  • -r (recursive): Essential for copying directories.
  • -a (archive): Preserves permissions, ownership, and timestamps. Equivalent to -dR --preserve=all.
  • -v (verbose): Print what is being done.
  • -i (interactive): Prompt before overwriting existing files.

Code Breakdown

8
Basic copy. If copy.txt already exists, it will be silently overwritten.
21
cp -r is mandatory when the source is a directory. It copies the folder structure and all files within it.