Skip to content

File Operations

File operations are essential when working with the command line. This section covers the basic commands for creating, copying, moving, and deleting files and directories.


touch

touch is used to create a new empty file or update the timestamp of an existing file.

touch filename.txt

touch_example.png

In this example, I used touch to create a new file called filename.txt.


mkdir

mkdir is used to create a new directory.

mkdir new_directory

mkdir_example.png

Here, I created a new directory called new_directory.

Here are some useful flags you can use with mkdir:

Flag Description
-p Create parent directories if they do not exist.

cp

cp is used to copy files or directories from one location to another.

cp source_file.txt destination_file.txt

cp_example.png

In this example, source_file.txt is copied to destination_file.txt.

Here are some useful flags you can use with cp:

Flag Description
-r Recursively copy directories and their contents.
-i Prompt before overwriting an existing file.
-u Copy only when the source file is newer than the destination file or when the destination file is missing.

mv

mv is used to move or rename files and directories.

mv old_name.txt new_name.txt

mv_example.png

In this example, old_name.txt is renamed to new_name.txt.

Here are some useful flags you can use with mv:

Flag Description
-i Prompt before overwriting an existing file.
-u Move only when the source file is newer than the destination file or when the destination file is missing.

rm

rm is used to remove files or directories.

rm filename.txt

rm_example.png

Here, filename.txt is deleted.

Here are some useful flags you can use with rm:

Flag Description
-r Recursively remove directories and their contents.
-i Prompt before each removal.
-f Force removal without prompt.

rmdir

rmdir is used to remove empty directories.

rmdir empty_directory

rmdir_example.png

In this example, empty_directory is removed because it is empty.


cat

cat is used to concatenate and display the content of files.

cat file.txt

cat_example.png

In this example, the content of file.txt is displayed.


less

less is used to view the content of a file page by page.

less file.txt

In this example, less is used to view file.txt.


vim, vi and nano

These are text editors used to edit files directly from the terminal.

vim file.txt
vi file.txt
nano file.txt

vim_example.png

In this example, vim is used to edit file.txt.

Note

Consider learning vim if you plan to do a lot of text editing in the terminal.

It has a steep learning curve but is very powerful once you get the hang of it.

Next Step

If you want to learn more about text processing, check out the Text Processing section in the Advanced Bash Commands guide.

But before that, let's move on to the next section on Variables to learn how to use variables in Bash scripts.

Previous | Next