RED HAT ENTERPRISE LINUX
Managing Files from the Command Line
Create, Copy, Move, and Delete Files and Directories
CIS126RH | RHEL System Administration 1 Mesa Coomunity College
Welcome to this essential module on managing files from the command line. File management is perhaps the most fundamental skill for any Linux administrator. Every day, you'll create configuration files, copy backups, move logs, organize directories, and clean up temporary files. While graphical file managers exist, the command line offers speed, precision, and the ability to work remotely over SSH. Today we'll master the core file management commands: creating files and directories, copying and moving them, and safely deleting what you no longer need. We'll also learn about wildcards for working with multiple files efficiently. These skills form the foundation for everything else you'll do in Linux administration.
Learning Objectives
1
Create files and directories
Use touch, mkdir, and text editors to create new items
2
Copy files and directories
Master the cp command with its essential options
3
Move and rename items
Use mv for moving and renaming files and directories
4
Delete files and directories safely
Remove items with rm and rmdir while avoiding disasters
We have four main learning objectives for this module. First, we'll learn to create files and directories using touch for empty files, mkdir for directories, and understand how text editors create files. Second, we'll master the cp command for copying, including the critical options for copying directories and preserving file attributes. Third, we'll use mv for both moving items to new locations and renaming them in place. Fourth, and perhaps most importantly, we'll learn to delete files and directories safely - the rm command is powerful but unforgiving, so we'll emphasize protective practices. Throughout, we'll also learn about wildcards that let you work with multiple files matching a pattern. Let's start with creating files and directories.
File Management Commands
touch
Create empty files or update timestamps
cp
Copy files and directories
mv
Move or rename files and directories
rm
Remove files and directories
rmdir
Remove empty directories only
Key Principle: These commands work silently on success. No output means the operation succeeded.
Let's get an overview of the core file management commands we'll master. touch creates empty files or updates the timestamp of existing files. mkdir creates directories. cp copies files and directories. mv moves items to new locations or renames them. rm removes files and directories, while rmdir removes only empty directories - a safer option when you want to ensure you're not deleting data. An important principle: these commands follow the Unix philosophy of silence on success. When a command works, it typically produces no output - only errors are reported. This can be disconcerting at first, but you'll appreciate it when scripting or working with many files. If you want confirmation, many commands accept a -v (verbose) option. These commands are your daily tools as an administrator. Let's examine each one in depth, starting with creating files and directories.
Creating Files: touch
touch [options] filename(s)
touch newfile.txt
touch file1.txt file2.txt file3.txt
touch "my document.txt"
touch existingfile.txt
ls -l newfile.txt
-rw-r--r--. 1 student student 0 Dec 7 10:30 newfile.txt
Note: If the file exists, touch updates its modification timestamp. If it doesn't exist, touch creates an empty (0 byte) file.
The touch command is the simplest way to create empty files. Its primary purpose is actually updating file timestamps, but creating empty files is a common use case. The basic syntax is simply touch followed by one or more filenames. You can create multiple files in a single command by listing them all. For filenames with spaces, quote the name or escape the spaces with backslashes. When touch operates on an existing file, it updates the modification and access timestamps to the current time without changing the contents. This is useful for triggering programs that watch for file changes or for adjusting file times. Note the file size in the ls output: 0 bytes. Touch creates truly empty files. To create a file with content, you'd use a text editor, redirection, or other commands. Why create empty files? Common uses include creating placeholder files, lock files that indicate a process is running, or files that will be populated later by scripts or applications.
Creating Directories: mkdir
mkdir [options] directory(ies)
mkdir projects
mkdir docs scripts logs
mkdir projects/webapp
mkdir -p projects/webapp/src/main
mkdir -m 700 private
mkdir -v newdir
mkdir: created directory 'newdir'
Pro Tip: Always use mkdir -p when creating nested paths - it creates missing parents and doesn't error if directory exists.
The mkdir command creates directories. The basic usage is straightforward: mkdir followed by the directory name. You can create multiple directories at once by listing them. When creating nested directories, the parent must exist. If you try mkdir projects/webapp/src and projects/webapp doesn't exist, you'll get an error. The -p option solves this by creating all necessary parent directories. It's also idempotent - it won't error if the directory already exists, making it safe for scripts. The -m option sets permissions at creation time rather than inheriting from umask and then modifying. mkdir -m 700 private creates a directory that only the owner can access. The -v option provides verbose output, confirming each directory creation. This is helpful when creating complex structures to verify everything was created. For most day-to-day use, mkdir -p is your friend - it handles the common case of creating directories with their full path without worrying about what already exists.
Other Ways to Create Files
vim newfile.txt
nano newfile.txt
echo "Hello World" > greeting.txt
echo "More text" >> greeting.txt
cat > config.txt << EOF
Setting1=value1
Setting2=value2
EOF
cp /etc/hosts myhosts
curl -o file.txt https://example.com/data.txt
Redirection: > creates/overwrites the file, >> appends to existing content.
Beyond touch, there are many ways to create files with content. Text editors like vim and nano create the file when you save, making them ideal for configuration files you need to edit anyway. Output redirection is extremely powerful. The greater-than symbol redirects command output to a file, creating it if it doesn't exist or overwriting if it does. Double greater-than appends instead of overwriting. This is crucial - accidentally using single redirect when you meant to append can destroy data. Heredocs (here documents) let you create multi-line files inline in scripts or at the command line. The content between << EOF and EOF goes into the file. Any word can replace EOF - it's just a delimiter. Copying creates a new file with existing content - useful for templates or backups. Commands like curl and wget download files from the web. Understanding these various methods helps you choose the right approach for each situation - touch for empty placeholders, redirection for command output, editors for files you need to write yourself.
Copying Files: cp
cp [options] source destination
cp original.txt backup.txt
cp report.txt /home/student/documents/
cp report.txt /home/student/documents/report_backup.txt
cp file1.txt file2.txt file3.txt /backup/
cp -v config.txt config.bak
'config.txt' -> 'config.bak'
The cp command copies files and directories. The basic syntax is cp followed by source and destination. When copying a single file, the destination can be a new filename (creating a copy with a different name) or a directory (keeping the original name in the new location). If you specify a directory as the destination, the file is copied into that directory with its original name. When copying multiple files, the destination must be a directory - you can't copy multiple sources to a single file destination. The -v option provides verbose output showing each copy operation, which is helpful for confirming what was copied, especially with wildcards. One important behavior: by default, cp overwrites existing files without warning. If /backup/report.txt already exists, cp report.txt /backup/ silently replaces it. We'll cover the -i option for interactive prompting to protect against accidental overwrites.
cp Options
Option
Purpose
When to Use
-r, -R
Recursive - copy directories
Required for copying directories
-i
Interactive - prompt before overwrite
Protect against accidental overwrites
-v
Verbose - show files being copied
Confirm operations, debugging
-p
Preserve mode, ownership, timestamps
Backups, maintaining file attributes
-a
Archive - preserve all (-pR + more)
Complete backups, cloning directories
-u
Update - copy only when source is newer
Incremental backups, syncing
-n
No clobber - don't overwrite existing
Safest copy mode
Let's examine the important cp options. The -r or -R option enables recursive copying, which is required for directories. Without it, trying to copy a directory produces an error. The -i option prompts before overwriting existing files. This is a safety net against accidentally replacing important files. Some administrators alias cp to 'cp -i' in their shell configuration. The -v option shows what's being copied, useful for confirmation or debugging. The -p option preserves the file's original mode (permissions), ownership, and timestamps. Without it, copied files get fresh timestamps and may have different permissions based on your umask. The -a option is archive mode - it combines -p with recursive copying and preserves links and other special files. This is ideal for backups or cloning directory trees. The -u option only copies when the source is newer than the destination or the destination doesn't exist. Great for incremental backups. The -n option prevents overwriting - if the destination exists, the copy is skipped. Understanding these options helps you copy files exactly as needed for each situation.
Copying Directories
cp -r projects/ projects_backup/
cp projects/ backup/
cp: -r not specified; omitting directory 'projects/'
cp -a /var/www/ /backup/www_backup/
cp -r projects/* /backup/projects/
cp -rp source_dir/ dest_dir/
cp -rv configs/ configs_backup/
'configs/app.conf' -> 'configs_backup/app.conf'
'configs/db.conf' -> 'configs_backup/db.conf'
⚠ Trailing Slash Matters: cp -r dir /dest/ copies dir INTO dest. cp -r dir/* /dest/ copies CONTENTS of dir into dest.
Copying directories requires the -r (recursive) option. Without it, cp refuses to copy directories. This is actually a safety feature - it prevents accidentally copying huge directory trees. When using -r, the destination behavior matters. If the destination doesn't exist, it's created as a copy of the source. If it exists and is a directory, the source is copied inside it. For backups, -a (archive) is often preferred because it preserves permissions, ownership, timestamps, symbolic links, and other attributes. This is especially important when copying system files where permissions matter. A subtle but important point: trailing slashes affect behavior. "cp -r dir /dest/" copies the directory "dir" into /dest/, resulting in /dest/dir/. If you want to copy the contents without the containing directory, use "cp -r dir/* /dest/" instead. With verbose mode, you can see every file being copied, which helps verify complex copy operations and catch any errors or skipped files.
Moving and Renaming: mv
mv [options] source destination
mv oldname.txt newname.txt
mv report.txt /home/student/documents/
mv draft.txt /final/published_report.txt
mv file1.txt file2.txt file3.txt /archive/
mv projects/ /home/student/work/
mv -v config.old config.new
renamed 'config.old' -> 'config.new'
Key Difference from cp: mv doesn't need -r for directories - it moves the entire directory in one operation.
The mv command serves two purposes: moving files to different locations and renaming them. In fact, renaming is just moving to a new name in the same directory. The syntax mirrors cp: mv source destination. For renaming, just specify the new name in the same directory. For moving, specify a directory as the destination. You can move and rename simultaneously by specifying a full path with a new filename. When moving multiple sources, the destination must be a directory. Unlike cp, mv does not require -r for directories. Moving a directory is actually a simple operation for the filesystem - it just updates the directory entry in the parent, rather than copying all the contents. This makes mv very fast even for large directories, as long as the source and destination are on the same filesystem. If they're on different filesystems, mv performs a copy-then-delete operation behind the scenes. Like cp, mv silently overwrites existing files by default. Use -i for interactive mode to get prompts before overwriting.
mv Options
mv -i source.txt destination.txt
mv: overwrite 'destination.txt'? y
mv -n source.txt destination.txt
mv -f source.txt destination.txt
mv -v *.log /var/log/archive/
'app.log' -> '/var/log/archive/app.log'
'error.log' -> '/var/log/archive/error.log'
mv -u updated.conf /etc/
mv --backup=numbered file.txt /dest/
# Creates /dest/file.txt.~1~ if file.txt exists
The mv options are similar to cp. The -i option prompts before overwriting existing files - answer y or n. This is your safety net against accidentally replacing important files. The -n option never overwrites - if the destination exists, the move is simply skipped. No error, no prompt, just skipped. The -f option forces the move, overwriting without prompting. This overrides -i if both are somehow specified (like through aliases). The -v option shows what's being moved, helpful when moving multiple files with wildcards to confirm the operation. The -u option only moves when the source is newer than the destination or the destination does