How to remove files and directories in the Linux operating system using the terminal?


The rm command is used to remove files and directories in the Linux operating system whereas the rmdir command is used to remove only empty directories.

rm (remove) – rm stands for remove. It is used for files, directories, and symbolic links from the Linux system. By default, it does not remove directories. In the Windows operating system, the same working functionality is provided by the del (delete) command. The rm command is also available in EFI (Extensible Firmware Interface) shell.

Note – Generally the rm command works silently so be careful while working with the rm command because after delete it is hard to recover the file.

Syntax

The general syntax of the rm command is as follows.

$ rm [OPTION]... FILE...

Brief description of options available in the rm command.

Sr.No.Option & Description
1-f, --force
Never prompt
2-i
Prompt a message before removal
3--no-preserve-root
Don’t treat ‘/’ specially
4-l, --link 
Create hard link of files instead of copying
5-R, -r, --recursive
Remove reclusively
6-v, --verbose
Explain what is happening
7--help
Display this help and exit
8--version
Output version information and exit

To remove a file from a directory, we use the rm command without any option as shown in below.

$ rm file.txt

To remove a file and prompt a confirmation message for removal, we use -i option with the rm command as shown in below.

$ rm -i file.txt
rm − remove regular file ‘file.txt’? y

To continue entering y or Y. After confirmation removal will be done.

The rmdir command is used to remove empty directories in the Linux system. The rmdir command removes a directory if specified directory is empty otherwise it will prompt an error message.

Syntax

The general syntax of the rmdir command is as follows −

$ rmdir [OPTION]... DIRECTORY...

Brief description of options available in the rmdir command.

Sr.No.Option & Description
1--ignore-fail-on-non-empty
Ignore failure message that directory is non-empty
2-p, --parents
Remove directory as well its parents’ directory
3-v, --verbose
Prompt a diagnostic for every directory processed
4--help
Display this help and exit
5--version
Output version information and exit

To remove an empty directory, we use the rmdir command in the Linux system using terminal.

First, we will create an empty directory using

$ mkdir new_dir

Then we will remove the created directory as shown in below.

$ rmdir new_dir

To remove an empty directory and prompt what is being done, we use -v or --verbose option with the rmdir command in the Linux system using terminal.

First, we will create an empty directory using

$ mkdir new_dir

Then we will remove the created directory and prompt what is being done as shown in below.

$ rmdir -v new_dir
rmdir − removing directory, ‘new_dir’

Updated on: 01-Jul-2021

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements