Bash 파일 및 디렉토리 처리

When working with the Linux command line, understanding how to handle files and directories is crucial. Bash, the default shell in most Linux distributions, provides a wealth of powerful tools for file and directory manipulation. In this blog post, we will explore some common tasks and commands for dealing with files and directories in Bash.

Listing Files and Directories

The ls command is used to list the files and directories in the current directory. Adding the -l flag will provide a detailed list, including file permissions, ownership, and size.

$ ls
file1.txt file2.txt directory1 directory2

$ ls -l
-rw-rw-r-- 1 user user 1024 Nov 23 10:00 file1.txt
-rw-rw-r-- 1 user user 2048 Nov 23 10:12 file2.txt
drwxrwxr-x 2 user user 4096 Nov 23 11:30 directory1
drwxrwxr-x 2 user user 4096 Nov 23 11:45 directory2

To navigate into a directory, use the cd command followed by the directory name.

$ cd directory1

To go back to the previous directory, use cd ...

Creating and Deleting Files and Directories

To create a file, use the touch command followed by the file name.

$ touch newfile.txt

To create a directory, use the mkdir command followed by the directory name.

$ mkdir newdirectory

To delete a file, use the rm command followed by the file name.

$ rm file1.txt

To delete an empty directory, use the rmdir command followed by the directory name.

$ rmdir directory1

To delete a directory and its contents, use the rm command with the -r flag (for recursive).

$ rm -r directory2

Renaming and Moving Files and Directories

To rename a file or directory, use the mv command followed by the current name and the new name.

$ mv file2.txt newfile.txt
$ mv directory2 newdirectory

To move a file or directory to a different location, use the mv command followed by the file/directory name and the destination directory.

$ mv newfile.txt newdirectory

Copying Files and Directories

To copy a file, use the cp command followed by the file name and the destination.

$ cp file2.txt backup/file2.txt

To copy a directory and its contents, use the cp command with the -r flag followed by the directory name and the destination.

$ cp -r directory1 backup/directory1

Searching for Files and Directories

The find command is used to search for files and directories in a specified location.

To find files matching a certain name, use the -name flag followed by the name or pattern.

$ find /path/to/search -name "*.txt"

To find directories, use the -type flag followed by d.

$ find /path/to/search -type d

Conclusion

The ability to handle files and directories effectively is essential for working in a Linux environment. With the commands and techniques covered in this blog post, you should now have a solid foundation for managing files and directories in Bash. Practice these commands and explore additional options to become more proficient in your Linux journey.