2.2.3. File operations
Table of Contents
Working with File Operations
File operations on the command line focus on creating, copying, moving, renaming, and removing files and directories. This chapter assumes you already know how to list files and move between directories, and it concentrates on what you can actually do to change the contents of the filesystem.
Creating Files
There are several common ways to create a new file from the command line. The simplest is the touch command. When used on a filename that does not exist, it creates an empty file. When used on an existing file, it updates its timestamps without changing the contents.
For example, to create an empty file in the current directory you can run touch notes.txt. If notes.txt is already present, this command does not overwrite any data. It only adjusts the access and modification times.
You can also create files by redirecting output from a command into a file. This is covered in more detail in the chapter on input and output redirection, but you should be aware of the basic idea here. For instance, echo "Hello" > hello.txt creates hello.txt with the contents Hello if the file did not exist before.
Important rule: touch filename never destroys file contents. Redirection with > replaces the existing contents of a file.
For interactive editing, you normally use a text editor such as nano or vim. Opening a non‑existent filename in these editors and saving it will also create the file.
Creating Directories
Directories are created with the mkdir command. At its simplest, mkdir newdir creates a directory called newdir in the current directory.
If you need to create a hierarchy of directories at once, you can use the -p option. For example, mkdir -p projects/2024/linux will create projects, then 2024 inside it, and then linux inside 2024, if any of those directories do not already exist. If some of them exist, -p tells mkdir not to treat that as an error.
Without -p, mkdir expects the parent directory to already exist. So mkdir projects/2024/linux fails if projects/2024 is missing.
Copying Files
Copying creates a new file or directory from an existing one. The basic command for copying is cp. When copying a single file into the current directory, the simplest form is cp source.txt copy.txt. This command reads source.txt and writes an identical file called copy.txt. If copy.txt already exists, by default cp overwrites it without asking.
You can also copy a file into a directory. If you have a directory called backup, you can run cp document.txt backup. The resulting path will be backup/document.txt. Linux decides whether the second argument is a file or directory based on what currently exists.
Important rule: cp source target overwrites target without confirmation if target exists, unless cp is given options such as -i.
To avoid accidental overwrites, many users add the interactive option -i which makes cp ask before replacing an existing file. For example, cp -i document.txt backup/ prompts you if backup/document.txt already exists.
Linux treats the source and destination as paths, so you can combine absolute and relative paths. For instance, cp /etc/hosts . copies the system hosts file into the current directory and keeps the same filename.
Copying Directories
Copying directories with cp requires an extra option. If you try cp dir1 dir2 and dir1 is a directory, this fails unless you tell cp to copy recursively. The recursive option -r or -R instructs cp to descend into directories and copy their contents.
To copy the directory dir1 and all its files and subdirectories into backup, you would run cp -r dir1 backup. If backup exists, you will end up with backup/dir1. If backup does not exist, dir1 is copied to a new directory called backup.
You can also include the -i option when copying directories. For example, cp -ri dir1 backup both recurses and asks before overwriting any existing files in backup/dir1.
Some distributions provide the -a option, which stands for "archive" and tells cp to copy recursively and also preserve attributes such as timestamps and permissions. For example, cp -a dir1 backup is a common pattern when making backups.
Moving and Renaming Files
Moving and renaming use the same command, mv. Conceptually, renaming is just moving a file to a new name in the same directory.
If you run mv oldname.txt newname.txt in a directory, you rename oldname.txt to newname.txt. If newname.txt already exists, it is replaced without asking unless you use -i.
Moving a file to a different directory uses the same pattern. For instance, mv report.txt documents/ moves report.txt into the directory documents. The resulting path is documents/report.txt. As with cp, Linux decides whether the second argument is a directory by looking at the actual filesystem.
If you want to move several files at once, you list them before the final directory. An example is mv file1.txt file2.txt documents/. This moves both file1.txt and file2.txt into documents.
The mv command is often faster than copying plus deleting because when you move files within the same filesystem, Linux usually just updates directory entries instead of rewriting file contents. When moving between different filesystems, for example from one disk to another, mv has to copy the data and then delete the original.
To avoid overwriting by mistake, you can use mv -i. When you run mv -i file.txt docs/, the command prompts if docs/file.txt already exists.
Important rule: mv overwrites existing files at the destination without prompting unless options like -i are used.
Moving and Renaming Directories
Directories can also be moved and renamed using mv. To rename a directory oldproject to newproject in the same location, run mv oldproject newproject. If a directory named newproject already exists, Linux tries to move oldproject inside it, which is a different result than a rename.
To move a directory into another directory, the syntax is the same. For example, mv project1 archive/ results in archive/project1. This move works even if project1 contains many files and subdirectories.
Because mv handles directories recursively without needing a special flag, you do not need an option like -r here. However, overwrite rules still apply to files inside directories when there are naming conflicts, so using -i can still be useful.
Removing Files
Removing files is a destructive operation. The basic command to remove a file is rm. For example, rm notes.txt deletes notes.txt from the current directory. There is no built‑in undo.
By default, rm does not ask for confirmation and silently removes the file. If the file does not exist, it prints an error message.
To add an extra layer of safety, many users prefer rm -i. This interactive mode asks for confirmation for each file: rm -i notes.txt prompts with something like rm: remove regular file 'notes.txt'?. You then answer y or n.
You can remove several files at once by listing them. For instance, rm file1.txt file2.txt report.pdf deletes all three. The -i option also applies here, so rm -i *.log lets you confirm each log file before it is deleted.
Important rule: rm permanently removes files. It does not send them to a trash can. Use interactive options or double‑check filenames before running.
Removing Directories
Directories require special care. To remove an empty directory, you can use either rmdir or rm -d. For example, rmdir emptydir only works if emptydir has no files or subdirectories.
To remove a directory and everything it contains, you must use a recursive option. The command rm -r dirname deletes the directory dirname and all files and subdirectories under it.
Because this is so destructive, many users prefer rm -ri dirname. This combination recurses and asks for confirmation before each deletion.
Some people use rm -rf dirname. The option -f stands for "force" and suppresses most warnings and prompts, even if files are write protected. This is powerful but dangerous, especially as the superuser, because it makes it much easier to delete important data or system files by mistake.
It is usually safer to start with a listing of what you are about to delete. For example, ls dirname or even ls -R dirname lets you see the contents before running a recursive removal.
Copying and Moving with Wildcards
Wildcards, also called globs, let you match multiple files with a single pattern. When used with cp, mv, or rm, they expand to a list of matching filenames before the command runs.
If you have several files like report1.txt, report2.txt, and report_final.txt, the pattern report.txt matches all of them. So cp report.txt backup/ copies all matching files into the backup directory.
You can move matching files in the same way. For example, mv *.jpg pictures/ moves all files ending in .jpg into the pictures directory.
Wildcards are processed by the shell, not by cp or mv. By the time the command runs, the shell has turned the pattern into a list of actual filenames.
Important rule: Wildcards expand to all matching files. Always double‑check a pattern with ls before using it with rm, cp, or mv.
One careful habit is to first run ls pattern to see which files match, then repeat the pattern with cp, mv, or rm once you are sure. For example, use ls .log before running rm .log.
Preserving Attributes While Copying
When you copy files, you may want to keep their permissions, owners, and timestamps. The cp command can do this using options. The -p option preserves mode, ownership, and timestamps where possible. For instance, cp -p original.txt copy.txt attempts to keep these attributes on copy.txt.
When you are copying entire directory trees, cp -a is convenient. It is typically equivalent to a combination such as -dR --preserve=all, which preserves symbolic links, attributes, and the structure of the tree while copying recursively. A typical backup command looks like cp -a /etc /backup/etc.
If you do not use these options, copied files may end up with the user, group, or timestamps of the copying process instead of matching the original.
Handling Overwrites and Prompts
Most file operations accept options that modify how they handle overwriting. For cp and mv, some of the most useful options are -i, -n, and -f.
The interactive option -i asks before overwriting. For example, cp -i file.txt backup/ or mv -i file.txt backup/ both prompt if a file with the same name already exists in the destination.
The -n option means "no clobber". It tells cp or mv never to overwrite existing files. With cp -n file.txt backup/, if backup/file.txt exists, the command skips copying without error and leaves the old file unchanged.
The -f or "force" option performs the opposite behavior. It suppresses prompts and attempts to overwrite without asking. Often this is combined with other options and used in scripts or automated tasks, but it should be used with care in interactive sessions.
When learning, preferring -i is usually safer. As you become more confident, you can choose when to rely on it and when to use noninteractive options.
Summary
File operations on the Linux command line rely on a small set of commands: touch and redirection to create files, mkdir to create directories, cp to copy, mv to move or rename, and rm or rmdir to delete. These commands become powerful when combined with wildcards and path handling. Always pay attention to when data might be overwritten or deleted permanently, and use interactive or preserving options when you need an extra margin of safety.
Views: 0
Where to Move
Move chapter:
- ☰ 1. PART I — Linux Fundamentals (Beginner)
- ☰ 1.1. What Is Linux?
- ☰ 1.1.1. What is an operating system
- ☰ 1.1.2. History of Unix and Linux
- ☰ 1.1.3. The Linux kernel
- ☰ 1.1.4. GNU and the Free Software Foundation
- ☰ 1.1.5. Open source philosophy
- ☰ 1.1.6. Where Linux is used today
- ☰ 1.1.7. Desktop vs server vs embedded Linux
-
- ☰ 1.2. Choosing a Linux Distribution
- ☰ 1.2.1. What is a distribution?
- ☰ 1.2.2. Package formats (deb, rpm, pacman)
- ☰ 1.2.3. Popular distributions
- ☰ 1.2.3.1. Ubuntu
- ☰ 1.2.3.2. Debian
- ☰ 1.2.3.3. Fedora
- ☰ 1.2.3.4. Arch Linux
- ☰ 1.2.3.5. openSUSE
-
- ☰ 1.2.4. Rolling vs fixed release
- ☰ 1.2.5. Choosing the right distribution
-
- ☰ 1.3. Installing Linux
- ☰ 1.3.1. Creating a bootable USB
- ☰ 1.3.2. Installing on real hardware
- ☰ 1.3.3. Dual booting with Windows
- ☰ 1.3.4. Installing in a virtual machine
- ☰ 1.3.5. Partitioning
- ☰ 1.3.5.1. `/` (root)
- ☰ 1.3.5.2. `/home`
- ☰ 1.3.5.3. Swap
-
- ☰ 1.3.6. First-time setup
-
- ☰ 1.4. First Steps After Installation
- ☰ 1.4.1. Desktop environment basics
- ☰ 1.4.2. Updating the system
- ☰ 1.4.3. Installing essential tools
- ☰ 1.4.4. Setting up drivers
- ☰ 1.4.5. Using the software center
-
- ☰ 1.5. Linux Filesystem Hierarchy
- ☰ 1.5.1. Overview of the root filesystem
- ☰ 1.5.2. Important directories
- ☰ 1.5.2.1. `/etc`
- ☰ 1.5.2.2. `/var`
- ☰ 1.5.2.3. `/usr`
- ☰ 1.5.2.4. `/tmp`
- ☰ 1.5.2.5. `/dev`
- ☰ 1.5.2.6. `/proc`
- ☰ 1.5.2.7. `/sys`
-
- ☰ 1.5.3. File types
- ☰ 1.5.4. Absolute vs relative paths
-
- ☰ 1.6. The Linux Graphical Environment
- ☰ 1.6.1. GNOME
- ☰ 1.6.2. KDE Plasma
- ☰ 1.6.3. XFCE
- ☰ 1.6.4. File managers
- ☰ 1.6.5. System settings
- ☰ 1.6.6. Workspaces and window management
-
-
- ☰ 2. PART II — Command Line Essentials
- ☰ 2.1. Terminal and Shell Basics
- ☰ 2.1.1. What is a shell?
- ☰ 2.1.2. Bash vs Zsh vs Fish
- ☰ 2.1.3. Command structure
- ☰ 2.1.4. Environment variables
- ☰ 2.1.5. Getting help
- ☰ 2.1.6. Command history and autocomplete
-
- ☰ 2.2. Files and Directories
- ☰ 2.2.1. Listing files
- ☰ 2.2.2. Navigating directories
- ☰ 2.2.3. File operations
- ☰ 2.2.4. Wildcards and globbing
- ☰ 2.2.5. Searching files
-
- ☰ 2.3. Viewing and Editing Text Files
- ☰ 2.3.1. Viewing tools
- ☰ 2.3.2. Editing with nano
- ☰ 2.3.3. Introduction to vim
- ☰ 2.3.4. Input/output redirection
-
- ☰ 2.4. Users, Permissions, and Ownership
- ☰ 2.4.1. Users and groups
- ☰ 2.4.2. Permission types (r, w, x)
- ☰ 2.4.3. Changing permissions
- ☰ 2.4.4. Changing ownership
- ☰ 2.4.5. Using sudo
-
- ☰ 2.5. Package Management
- ☰ 2.5.1. Software repositories
- ☰ 2.5.2. APT (Debian/Ubuntu)
- ☰ 2.5.3. DNF (Fedora/RHEL)
- ☰ 2.5.4. Pacman (Arch Linux)
- ☰ 2.5.5. Snap, Flatpak, AppImage
- ☰ 2.5.6. System upgrades
-
- ☰ 2.6. Working with Processes
- ☰ 2.6.1. What is a process?
- ☰ 2.6.2. Viewing processes
- ☰ 2.6.3. Killing processes
- ☰ 2.6.4. Foreground and background jobs
- ☰ 2.6.5. System services and daemons
-
- ☰ 2.7. Introduction to Shell Scripting
- ☰ 2.7.1. Writing your first script
- ☰ 2.7.2. Variables
- ☰ 2.7.3. Conditionals
- ☰ 2.7.4. Loops
- ☰ 2.7.5. Functions
- ☰ 2.7.6. Making scripts executable
-
-
- ☰ 3. PART III — Intermediate System Administration
- ☰ 3.1. Systemd and Service Management
- ☰ 3.1.1. What is systemd?
- ☰ 3.1.2. Managing services (systemctl)
- ☰ 3.1.3. Boot targets
- ☰ 3.1.4. System logs (journalctl)
- ☰ 3.1.5. Creating custom services
-
- ☰ 3.2. Storage and Filesystems
- ☰ 3.2.1. Devices and partitions
- ☰ 3.2.2. Filesystems (EXT4, XFS, Btrfs)
- ☰ 3.2.3. Mounting and unmounting
- ☰ 3.2.4. Disk usage tools
- ☰ 3.2.5. Archiving and compression (tar, gzip, xz)
-
- ☰ 3.3. Networking Fundamentals
- ☰ 3.3.1. IP addressing
- ☰ 3.3.2. Subnets and routing
- ☰ 3.3.3. DNS and hostnames
- ☰ 3.3.4. Networking tools (ip, ss, ping)
- ☰ 3.3.5. Editing network configuration files
-
- ☰ 3.4. User and Group Administration
- ☰ 3.4.1. User information files
- ☰ 3.4.2. Creating and removing users
- ☰ 3.4.3. Password policies
- ☰ 3.4.4. Managing groups
- ☰ 3.4.5. Shell configuration
-
- ☰ 3.5. System Monitoring
- ☰ 3.5.1. CPU and memory monitoring
- ☰ 3.5.2. Disk and I/O monitoring
- ☰ 3.5.3. Log files in /var/log
- ☰ 3.5.4. Boot performance
- ☰ 3.5.5. Monitoring running services
-
- ☰ 3.6. Backup and Restore
- ☰ 3.6.1. Backup strategies
- ☰ 3.6.2. Using rsync
- ☰ 3.6.3. Creating tar archives
- ☰ 3.6.4. Using snapshot systems
- ☰ 3.6.5. Automating backups
-
- ☰ 3.7. Basic System Security
- ☰ 3.7.1. Firewalls (UFW, firewalld)
- ☰ 3.7.2. Authentication policies
- ☰ 3.7.3. SSH security basics
- ☰ 3.7.4. SELinux and AppArmor overview
- ☰ 3.7.5. Intrusion detection basics
-
-
- ☰ 4. PART IV — Advanced Linux Skills
- ☰ 4.1. Advanced Shell Scripting
- ☰ 4.1.1. Script structure
- ☰ 4.1.2. Error handling
- ☰ 4.1.3. Debugging scripts
- ☰ 4.1.4. Scheduled tasks (cron)
-
- ☰ 4.2. The Linux Boot Process
- ☰ 4.2.1. BIOS vs UEFI
- ☰ 4.2.2. Understanding GRUB2
- ☰ 4.2.3. Kernel loading
- ☰ 4.2.4. initramfs
- ☰ 4.2.5. Troubleshooting boot issues
-
- ☰ 4.3. Kernel Management
- ☰ 4.3.1. What is the kernel?
- ☰ 4.3.2. Kernel modules
- ☰ 4.3.3. Kernel parameters
- ☰ 4.3.4. Compiling a custom kernel
- ☰ 4.3.5. Kernel versioning and updates
-
- ☰ 4.4. Advanced Filesystems and Storage
- ☰ 4.4.1. LVM concepts
- ☰ 4.4.2. Logical volumes
- ☰ 4.4.3. RAID levels
- ☰ 4.4.4. Full disk encryption (LUKS)
- ☰ 4.4.5. Snapshots and rollbacks
-
- ☰ 4.5. Network Services
- ☰ 4.5.1. SSH server configuration
- ☰ 4.5.2. NFS
- ☰ 4.5.3. Samba
- ☰ 4.5.4. FTP/SFTP
- ☰ 4.5.5. Firewalls in depth
-
- ☰ 4.6. Logging and Auditing
- ☰ 4.6.1. Systemd logging
- ☰ 4.6.2. Traditional logs in /var/log
- ☰ 4.6.3. Auditd
- ☰ 4.6.4. Log rotation
- ☰ 4.6.5. Creating custom logs
-
- ☰ 4.7. Virtualization and Containers
- ☰ 4.7.1. Virtual machines (KVM/QEMU)
- ☰ 4.7.2. Linux containers (LXC/LXD)
- ☰ 4.7.3. Docker fundamentals
- ☰ 4.7.4. Podman vs Docker
- ☰ 4.7.5. Container networking
-
-
- ☰ 5. PART V — Server Administration (Expert)
- ☰ 5.1. Web Servers
- ☰ 5.1.1. Apache basics
- ☰ 5.1.2. Nginx basics
- ☰ 5.1.3. Virtual hosts
- ☰ 5.1.4. SSL/HTTPS
- ☰ 5.1.5. Reverse proxy concepts
-
- ☰ 5.2. Database Servers
- ☰ 5.2.1. MySQL/MariaDB
- ☰ 5.2.2. PostgreSQL
- ☰ 5.2.3. Database backup strategies
- ☰ 5.2.4. Database hardening
-
- ☰ 5.3. Email Services
- ☰ 5.3.1. SMTP fundamentals
- ☰ 5.3.2. Configuring Postfix
- ☰ 5.3.3. IMAP/POP3 with Dovecot
- ☰ 5.3.4. Spam filtering systems
- ☰ 5.3.5. Email routing concepts
-
- ☰ 5.4. DNS and DHCP
- ☰ 5.4.1. Understanding DNS
- ☰ 5.4.2. Setting up BIND
- ☰ 5.4.3. DNS zones and records
- ☰ 5.4.4. DHCP server configuration
- ☰ 5.4.5. DNS troubleshooting
-
- ☰ 5.5. Load Balancing
- ☰ 5.5.1. HAProxy fundamentals
- ☰ 5.5.2. Nginx as a load balancer
- ☰ 5.5.3. Session persistence
- ☰ 5.5.4. High availability concepts
-
- ☰ 5.6. Clustering and High Availability
- ☰ 5.6.1. Failover principles
- ☰ 5.6.2. Pacemaker
- ☰ 5.6.3. Corosync
- ☰ 5.6.4. Cluster resource management
- ☰ 5.6.5. Distributed filesystems
-
-
- ☰ 6. PART VI — DevOps and Cloud
- ☰ 6.1. Linux for Developers
- ☰ 6.1.1. Compiler toolchains (gcc, make)
- ☰ 6.1.2. Git fundamentals
- ☰ 6.1.3. Debugging tools (gdb, strace)
- ☰ 6.1.4. Build automation (Makefile, CMake)
-
- ☰ 6.2. DevOps on Linux
- ☰ 6.2.1. CI/CD principles
- ☰ 6.2.2. YAML basics
- ☰ 6.2.3. GitHub Actions
- ☰ 6.2.4. GitLab CI/CD
- ☰ 6.2.5. Automated testing
-
- ☰ 6.3. Configuration Management
- ☰ 6.3.1. Ansible basics
- ☰ 6.3.2. Playbooks and inventories
- ☰ 6.3.3. Puppet overview
- ☰ 6.3.4. Chef overview
-
- ☰ 6.4. Infrastructure as Code
- ☰ 6.4.1. Terraform fundamentals
- ☰ 6.4.2. Providers and resources
- ☰ 6.4.3. Modules
- ☰ 6.4.4. Cloud provisioning with Terraform
-
- ☰ 6.5. Cloud Computing with Linux
- ☰ 6.5.1. Linux on AWS
- ☰ 6.5.2. Linux on Azure
- ☰ 6.5.3. Linux on GCP
- ☰ 6.5.4. Cloud networking basics
- ☰ 6.5.5. Scaling and monitoring
-
-
- ☰ 7. PART VII — Master Topics
- ☰ 7.1. Hardening a Linux System
- ☰ 7.1.1. Hardening principles
- ☰ 7.1.2. Kernel hardening
- ☰ 7.1.3. File integrity monitoring
- ☰ 7.1.4. Vulnerability scanning
-
- ☰ 7.2. Forensics and Incident Response
- ☰ 7.2.1. Collecting evidence
- ☰ 7.2.2. Log and file recovery
- ☰ 7.2.3. Analyzing suspicious processes
- ☰ 7.2.4. Incident response workflow
-
- ☰ 7.3. Performance Tuning
- ☰ 7.3.1. CPU tuning
- ☰ 7.3.2. Memory tuning
- ☰ 7.3.3. Disk and I/O optimization
- ☰ 7.3.4. Profiling tools
-
- ☰ 7.4. Writing Linux Tools
- ☰ 7.4.1. Bash-based tools
- ☰ 7.4.2. Python command-line tools
- ☰ 7.4.3. Writing tools in C
- ☰ 7.4.4. Using Linux system APIs
-
- ☰ 7.5. Linux Internals
- ☰ 7.5.1. Process lifecycle
- ☰ 7.5.2. Memory management
- ☰ 7.5.3. Signals and IPC
- ☰ 7.5.4. Namespaces
- ☰ 7.5.5. cgroups
-
- ☰ 7.6. Becoming a Linux Expert
- ☰ 7.6.1. Career paths
- ☰ 7.6.2. Certifications (RHCE, LFCS, LPIC)
- ☰ 7.6.3. Building a homelab
- ☰ 7.6.4. Contributing to open source
-
-
Comments
Please login to add a comment.
Don't have an account? Register now!