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.