How to create and remove files in Linux

This blog post will teach you how to create and remove files in Linux using the command line. You will learn how to create new files, directories, and links, as well as how to delete them

Creating and Removing Files

  • touch – create empty files or update file timestamps
  • rm – remove files
  • Usage:
    • rm [option]<file>…
  • Example:
    • rm -i file (interactive)
    • rm -r directory (recursive)
    • rm -f file (force)

Creating and modifying files with touch

touch updates a file’s timestamps. For example, if the last time you accessed a file was at 12:02 pm and you touch the file at 12:45 pm, the file will show its last access at 12:45 pm. If you touch a file that does not exist, an empty file will be created.

Removing files with rm

rm removes files. One or more files can be targets for removal. By default, rm will not remove directories. The -r option tells rm to remove files recursively and thus it will delete directories and their contents.

To remove a directory and all files and subdirectories it contains, suppressing and ignoring warnings about removing write-protected files and directories, use rm -rf. Be very careful not to erase needed files with this option! If necessary, rm command can be made interactive with -i.

There is no way to undo the effects of rm, except to restore from a backup.

Examples:

Remove a directory and all its contents.

amar@amar-pc:~/Desktop$ rm -r abcd
How to create and remove files in Linux

Use -r in combination with -i to recurse through the named directory and to query whether or not each file should be removed. The file will be removed if the user types y or Y.

amar@amar-pc:~/Desktop$ rm -ri abcd
rm: descend into directory 'abcd'? y
rm: remove regular empty file 'abcd/abcd.txt'? y
rm: remove directory 'abcd/AB'? y
rm: remove regular empty file 'abcd/xyz.txt'? y
rm: remove directory 'abcd/xyz'? y
rm: remove directory 'abcd'? y
How to create and remove files in Linux

Use -f to suppress warnings about write-protected files. If the example above had used rm -rf instead of rm -ri, the directory tree would have been deleted with no further prompting.

Note:
The default behavior of rm depends on upon who you are logged in as. Normally rm never prompts for configuration before removing a file (-f behavior). However, in Red Hat Enterprise Linux, the root user has special settings that cause rm to always prompt (-i behavior). Knowing about these

Leave a Comment