Mastering Linux File Operations: Creating and Moving Files | Linux

2024/01/03

In the Linux command line world, proficiently creating and moving files is a fundamental skill. This is typically the most frequently used command when working with Linux systems on the job.

Creating Files in Linux:

  1. touch Command:
  • Creates an empty file or updates the access and modification timestamps of an existing file.
touch filename
  1. echo Command:
  • Adds content to a file. Used to create and populate text files.
echo "content" > filename

Moving and Renaming Files:

  1. mv Command:
  • Moves or renames files and directories. This is a versatile command for organizing file structures.
mv source destination

Demo Commands:

# Create a file
touch <new file name>

# Delete a file
rm <file name>
# Delete a directory/folder
rm -r <folder name or folder path>
# Forcefully delete a folder and all files within it
rm -rf <file or folder path>

# Copy a file
cp <source file> <destination file>
# Copy a directory (note: all files within the directory will also be copied)
cp -r <source folder> <destination folder>

# Move or rename
mv <source file path> <target file path>

# When moving a large number of files, we first pack multiple files or directories into a tar archive
tar -cf <name>.tar <source file> <source folder> ...
# When moving a large number of files with large sizes, we can use compression to reduce the .tar file size (note: the extension changes to .tar.gz), which also speeds up transfers
tar -zcf <name>.tar.gz <source file> <source folder> ...
# Extract contents to a specified directory
tar -xzf <name>.tar.gz -C <target folder name(existing)>

Benefits of Mastering File Moving and Renaming:

Mastering file creation and movement allows you to efficiently organize file structures. Combined with other commands, you can quickly create large numbers of files as needed.

Important Note:

In Linux systems, unlike Windows or Mac OS, there is no Trash Bin. Once you execute rm, the file or directory is gone forever, so be extremely careful when running the rm command.

Linux Trash Bin

Trash Bin (trash)

You can install the trash package, which temporarily stores deleted files in a trash bin and only permanently deletes them after 30 days. This gives you a trash bin experience similar to Windows or Mac OS when deleting files, so even if you make a mistake, you can still recover them.