Skip to content

File Operations

Overview

This chapter introduces the most commonly used file and directory operations in Linux, including creating, copying, moving, deleting, viewing, and other operations.

Creating Files and Directories

touch - Create Empty Files

bash
# Create single file
$ touch file.txt

# Create multiple files
$ touch file1.txt file2.txt file3.txt

# Use brace expansion
$ touch file{1..5}.txt
# Creates file1.txt, file2.txt, file3.txt, file4.txt, file5.txt

# Update existing file's timestamp
$ touch existing_file.txt

mkdir - Create Directories

bash
# Create single directory
$ mkdir mydir

# Create multiple directories
$ mkdir dir1 dir2 dir3

# Create directory recursively (including parent directories)
$ mkdir -p parent/child/grandchild

# Create directory and set permissions
$ mkdir -m 755 mydir

Copying Files and Directories

cp - Copy

bash
# Copy file
$ cp source.txt dest.txt

# Copy to directory
$ cp file.txt /path/to/directory/

# Copy multiple files to directory
$ cp file1.txt file2.txt /path/to/directory/

# Copy directory (requires -r option)
$ cp -r source_dir/ dest_dir/

# Common options
$ cp -i file.txt dest/     # Prompt before overwriting
$ cp -v file.txt dest/     # Show detailed information
$ cp -u file.txt dest/     # Copy only if source is newer
$ cp -p file.txt dest/     # Preserve file attributes (permissions, time, etc.)
$ cp -a source/ dest/      # Archive mode, preserve all attributes

Common Options Description

OptionDescription
-r, -RRecursive directory copy
-iPrompt before overwriting
-vShow detailed process
-uCopy only newer files
-pPreserve file attributes
-aArchive mode (equivalent to -dR --preserve=all)
-fForce overwrite

Example Scenarios

bash
# Backup file
$ cp config.txt config.txt.bak

# Copy directory and all its contents
$ cp -r project/ project_backup/

# Copy while preserving all attributes
$ cp -a /var/www/html/ /backup/www/

# Copy only new or modified files
$ cp -u *.txt /backup/

Moving and Renaming

mv - Move/Rename

bash
# Rename file
$ mv oldname.txt newname.txt

# Move file to directory
$ mv file.txt /path/to/directory/

# Move multiple files
$ mv file1.txt file2.txt /path/to/directory/

# Move and rename
$ mv file.txt /path/to/directory/newname.txt

# Move directory
$ mv source_dir/ /path/to/destination/

# Common options
$ mv -i file.txt dest/     # Prompt before overwriting
$ mv -v file.txt dest/     # Show detailed information
$ mv -u file.txt dest/     # Move only if source is newer
$ mv -f file.txt dest/     # Force move

Common Options Description

OptionDescription
-iPrompt before overwriting
-vShow detailed process
-uMove only newer files
-fForce overwrite
-nDon't overwrite existing files

Batch Renaming

bash
# Use rename command (needs installation)
# Debian/Ubuntu
$ sudo apt install rename

# Change all .txt to .md
$ rename 's/\.txt$/.md/' *.txt

# Convert filenames to lowercase
$ rename 'y/A-Z/a-z/' *

# Add prefix
$ rename 's/^/prefix_/' *.txt

Deleting Files and Directories

rm - Delete

bash
# Delete file
$ rm file.txt

# Delete multiple files
$ rm file1.txt file2.txt

# Delete using wildcards
$ rm *.txt

# Delete directory (requires -r option)
$ rm -r directory/

# Force delete (no prompt)
$ rm -f file.txt

# Delete directory and its contents
$ rm -rf directory/

# Prompt before deleting
$ rm -i file.txt

# Show deletion process
$ rm -v file.txt

Common Options Description

OptionDescription
-r, -RRecursive directory delete
-fForce delete, no prompt
-iPrompt before deleting
-vShow detailed process

Warning: rm -rf is a dangerous command! Mistakes can lead to data loss. It's recommended to:

  • Confirm content with ls before deleting
  • Use -i option to confirm
  • Consider using trash-cli instead of direct deletion

rmdir - Delete Empty Directory

bash
# Delete empty directory
$ rmdir empty_dir/

# Recursively delete empty parent directories
$ rmdir -p parent/child/grandchild/

Safe Deletion: trash-cli

bash
# Install
$ sudo apt install trash-cli

# Move file to trash
$ trash-put file.txt

# List trash contents
$ trash-list

# Restore file
$ trash-restore

# Empty trash
$ trash-empty

Viewing File Contents

cat - Display All Content

bash
# Display file content
$ cat file.txt

# Show line numbers
$ cat -n file.txt

# Show non-printing characters
$ cat -A file.txt

# Merge multiple files
$ cat file1.txt file2.txt > combined.txt

less - Paginated Viewing

bash
$ less file.txt

Navigation Keys

KeyFunction
Space / fNext page
bPrevious page
j / Next line
k / Previous line
gJump to beginning
GJump to end
/patternSearch forward
?patternSearch backward
nNext search result
NPrevious search result
qQuit

more - Simple Pagination

bash
$ more file.txt
# Press space to page, q to quit

head - Display Beginning

bash
# Display first 10 lines (default)
$ head file.txt

# Display first 20 lines
$ head -n 20 file.txt
$ head -20 file.txt

# Display first 100 bytes
$ head -c 100 file.txt

tail - Display End

bash
# Display last 10 lines (default)
$ tail file.txt

# Display last 20 lines
$ tail -n 20 file.txt
$ tail -20 file.txt

# Follow file updates in real-time
$ tail -f /var/log/syslog

# Display starting from line 100
$ tail -n +100 file.txt

File Information

stat - Detailed File Information

bash
$ stat file.txt
  File: file.txt
  Size: 1234            Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d      Inode: 12345678    Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/ maxwell)   Gid: ( 1000/ maxwell)
Access: 2025-01-01 10:00:00.000000000 +0800
Modify: 2025-01-01 09:00:00.000000000 +0800
Change: 2025-01-01 09:00:00.000000000 +0800
 Birth: 2025-01-01 08:00:00.000000000 +0800

file - File Type

bash
$ file document.pdf
document.pdf: PDF document, version 1.4

$ file image.png
image.png: PNG image data, 1920 x 1080, 8-bit/color RGBA

$ file script.sh
script.sh: Bourne-Again shell script, ASCII text executable

wc - Statistics

bash
# Count lines, words, bytes
$ wc file.txt
   100   500  3000 file.txt
# 100 lines, 500 words, 3000 bytes

# Show only lines
$ wc -l file.txt
100 file.txt

# Show only words
$ wc -w file.txt

# Show only bytes
$ wc -c file.txt

# Show characters
$ wc -m file.txt

# Count multiple files
$ wc -l *.txt

du - Disk Usage

bash
# Directory size
$ du -h directory/
4.0K    directory/subdir
8.0K    directory/

# Show only total
$ du -sh directory/
8.0K    directory/

# Show each file's size
$ du -ah directory/

# Sort by size
$ du -h directory/ | sort -h

Hard links are multiple filenames pointing to the same inode.

bash
# Create hard link
$ ln original.txt hardlink.txt

# Verify (same inode number)
$ ls -li original.txt hardlink.txt
12345 -rw-r--r-- 2 user user 100 Jan 1 10:00 hardlink.txt
12345 -rw-r--r-- 2 user user 100 Jan 1 10:00 original.txt

Features

  • Deleting original file doesn't affect hard link
  • Cannot cross filesystems
  • Cannot link directories

Symbolic links are special files pointing to another file's path.

bash
# Create symbolic link
$ ln -s /path/to/original.txt symlink.txt

# View what link points to
$ ls -l symlink.txt
lrwxrwxrwx 1 user user 20 Jan 1 10:00 symlink.txt -> /path/to/original.txt

# Read link target
$ readlink symlink.txt
/path/to/original.txt

# Read absolute path
$ readlink -f symlink.txt

Features

  • Can cross filesystems
  • Can link directories
  • Link becomes broken if original file is deleted
FeatureHard LinkSymbolic Link
Cross filesystemNoYes
Link directoryNoYes
Original deletedStill accessibleLink broken
inodeSameDifferent
File sizeSame as originalStores path size

Directory Operations

ls - List Directory Contents

bash
# Basic listing
$ ls

# Detailed information
$ ls -l

# Show hidden files
$ ls -a

# Human-readable sizes
$ ls -lh

# Sort by time
$ ls -lt

# Sort by size
$ ls -lS

# Recursive display
$ ls -R

# Show directory itself
$ ls -d */

# Common combinations
$ ls -lah

Understanding ls -l Output

-rw-r--r-- 1 maxwell maxwell 1234 Jan 1 10:00 file.txt
│├──┼──┼──┤ │ │       │       │    │           │
│ │  │  │  │ │       │       │    │           └─ Filename
│ │  │  │  │ │       │       │    └─ Modification time
│ │  │  │  │ │       │       └─ File size (bytes)
│ │  │  │  │ │       └─ Group
│ │  │  │  │ └─ Owner
│ │  │  │  └─ Link count
│ │  │  └─ Other user permissions
│ │  └─ Group permissions
│ └─ Owner permissions
└─ File type

tree - Tree Display

bash
# Install
$ sudo apt install tree

# Basic usage
$ tree
.
├── dir1
   ├── file1.txt
   └── file2.txt
└── dir2
  └── file3.txt

# Show only directories
$ tree -d

# Limit depth
$ tree -L 2

# Show hidden files
$ tree -a

# Show file sizes
$ tree -h

Compression and Archiving

tar - Archive

bash
# Create archive
$ tar -cvf archive.tar files/
# c: create, v: verbose, f: filename

# Extract archive
$ tar -xvf archive.tar

# Create gzip compressed archive
$ tar -czvf archive.tar.gz files/

# Extract gzip archive
$ tar -xzvf archive.tar.gz

# Create bzip2 compressed archive
$ tar -cjvf archive.tar.bz2 files/

# Create xz compressed archive
$ tar -cJvf archive.tar.xz files/

# Extract to specific directory
$ tar -xzvf archive.tar.gz -C /path/to/dest/

# View archive contents
$ tar -tvf archive.tar

Options Description

OptionDescription
-cCreate archive
-xExtract archive
-tList contents
-vVerbose output
-fSpecify filename
-zgzip compression
-jbzip2 compression
-Jxz compression
-CExtract to specified directory

gzip / gunzip

bash
# Compress file (original file will be deleted)
$ gzip file.txt
# Produces file.txt.gz

# Preserve original file
$ gzip -k file.txt

# Decompress
$ gunzip file.txt.gz
$ gzip -d file.txt.gz

zip / unzip

bash
# Compress files
$ zip archive.zip file1.txt file2.txt

# Compress directory
$ zip -r archive.zip directory/

# Decompress
$ unzip archive.zip

# Decompress to specific directory
$ unzip archive.zip -d /path/to/dest/

# View contents
$ unzip -l archive.zip

Practical Tips

Safe Operation Aliases

bash
# Add to ~/.bashrc
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

Batch Operations

bash
# Create multiple directories
$ mkdir -p project/{src,bin,doc,test}

# Copy specific type files
$ cp *.txt backup/

# Delete specific type files
$ rm -f *.tmp

# Move multiple files
$ mv file{1..5}.txt dest/

Find Large Files

bash
# Find files larger than 100MB
$ find . -size +100M -ls

# Sort directories by size
$ du -h --max-depth=1 | sort -hr

Summary

This chapter introduced core Linux file operation commands:

  • Creating: touch, mkdir
  • Copying: cp
  • Moving/Renaming: mv
  • Deleting: rm, rmdir
  • Viewing: cat, less, head, tail
  • Information: stat, file, wc, du
  • Links: ln
  • Directories: ls, tree
  • Compression: tar, gzip, zip

Mastering these commands is the foundation of using Linux. Practice them frequently and they'll soon become your powerful tools.


Previous chapter: File System Structure

Next chapter: File Permissions

Content is for learning and research only.