Bash File Operations - ls, cp, mv, rm, find, chmod

Complete guide to bash file operations including listing, copying, moving, removing, finding, and changing permissions on files and directories.

File Operations

Detailed Explanation

File Operations in Bash

File operations are the foundation of working in a Unix/Linux shell. Bash provides a rich set of built-in commands and external utilities for creating, copying, moving, searching, and managing files and directories.

Listing Files with ls

The ls command is the most frequently used command in bash. It lists directory contents with various formatting options:

ls -lah          # long listing, all files, human-readable sizes
ls -lt           # sorted by modification time
ls -lS           # sorted by file size
ls -d */         # list only directories
ls -R            # recursive listing

The -l flag shows permissions, owner, group, size, and modification date. The -a flag includes hidden files (those starting with a dot).

Copying with cp

The cp command copies files and directories. For directories, you must use the -r (recursive) flag:

cp file.txt backup.txt        # copy a file
cp -r src/ src_backup/        # copy a directory
cp -rp /data/ /backup/data/   # copy preserving permissions and timestamps

Moving and Renaming with mv

The mv command both moves and renames files. There is no separate rename command in bash:

mv old.txt new.txt           # rename a file
mv file.txt ~/Documents/     # move to another directory
mv *.log /var/log/archive/   # move multiple files

Removing with rm

The rm command permanently deletes files. Unlike graphical file managers, there is no recycle bin:

rm file.txt          # remove a file
rm -rf directory/    # remove directory and all contents (use with caution)
rm -i important.txt  # prompt before removal

Finding Files with find

The find command searches directory trees based on name, type, size, modification time, and other criteria:

find . -name "*.js" -type f            # find JS files
find /home -size +100M                  # find files over 100MB
find . -mtime -1                        # modified in last 24 hours
find . -name "*.log" -exec rm {} \;    # find and delete log files

Changing Permissions with chmod

The chmod command modifies file permissions using either octal (numeric) or symbolic notation:

chmod 755 script.sh    # rwxr-xr-x
chmod 644 config.yaml  # rw-r--r--
chmod +x deploy.sh     # add execute permission
chmod -R 750 project/  # recursive permission change

Use Case

File operations are essential for every bash user. System administrators use them to manage server files, developers use them in build scripts and deployment automation, and DevOps engineers use them in CI/CD pipelines. Understanding these commands is the first step to becoming productive in a Unix/Linux environment.

Try It — Bash Cheat Sheet

Open full tool