Working with Files and Directories

Working with Files and Directories

In this section, we will explore how to create, manipulate, and delete files and directories in Linux.


Creating Files and Directories

To create a new file or directory, we can use the touch and mkdir commands respectively.

To create a new file, we can use the following command:

touch filename 

To create a new directory, we can use the following command:

mkdir directoryname 


Listing Files and Directories

To view the contents of a directory, we can use the ls command. By default, the ls command will display the files and directories in the current directory.

ls 

To view the contents of a specific directory, we can specify the directory path after the ls command:

ls /path/to/directory 


Moving and Renaming Files and Directories

To move a file or directory from one location to another, we can use the mv command.

mv sourcefile destination 

To rename a file or directory, we can also use the mv command:

mv oldfilename newfilename 


Copying Files and Directories

To copy a file, we can use the cp command.

cp sourcefile destination 

To copy a directory and its contents, we can use the -r (recursive) flag with the cp command:

cp -r sourcedirectory destination 


Deleting Files and Directories

To delete a file, we can use the rm command:

rm filename 

To delete an empty directory, we can use the rmdir command:

rmdir directoryname 

To delete a directory and its contents, we can use the rm command with the -r (recursive) flag:

rm -r directoryname 

As with any deletion command, use caution to ensure that you are deleting only the files and directories that you intend to delete.

Complete and Continue