The Linux Newbie Guide  ⇒    Fundamentals     Advanced     Supplement   Command Index   ENG⇒中
All rights reserved, please indicate the source when citing
 

 File Operations

Basic File Operations
       Link Files
           Symbolic Link
           Hard Link
       ln : Create File Link
       cp : File Copy
       rm : File Delete
       mv : File Move
       "\ " : Escape Character
ENG⇒中ENG⇒中
 

  Basic File Operations
Basic file operations include copying, moving, deleting, and renaming files or directories. However, these operations may involve not only the actual files or directories but also their doppelgangers called "linked files." Therefore, it is necessary to understand "linked files."

Link Files
Linked files are somewhat similar to Windows "shortcuts," but not exactly the same. In Windows, a "shortcut" is an actual file that takes up space and has the file extension ".lnk." A shortcut file (".lnk") does not directly contain the content but rather records the path of a specific file. Its purpose is to significantly save storage space. For example, a file or directory may be 1GB in size, but its shortcut file (".lnk") is usually less than 0.5KB in size because the shortcut file only records the path and other attributes of the source file (such as executable files, which may include launch parameters and launch locations).

Linux uses the ext2/ext3/ext4 file system standard, where the file system information is recorded in inodes, and the content is recorded in blocks. Linked files in Linux can use inodes to record the path of the source file without necessarily involving blocks. Therefore, Linux linked files may not occupy actual space like Windows "shortcuts" typically do.

There are two types of linked files in Linux: symbolic links and hard links. The differences are as follows.





^ back on top ^

ln : Create File Link
Now that you know the link file, let’s observe and practice it. The usage of the command ln to create a file link is as follows:

Syntax:ln [-otpiton][--option] source target_link_file
Command name/Function/Command use Options Function
ln/
Create a link/
Any
-s Create a Symbolic Link, if there is no such option, the default is a Hard Link
-b If the link file to be created already exists, it will automatically back up the existing file first (add "~" at the end of the backup file)
-f If the link file to be created already exists, overwrite the old file
--help Displays the command's built-in help and usage information


Example: (symbolic link)
$ ls -lgGh /usr/share/dict/ ←check directory "/usr/share/dict/" size
-rw-r--r--. 1 4.8M May 16 2010 linux.words ←Directory size 4.8M
$ ln -s /usr/share/dict/ s_link ←Create a symbolic link file "s_link" to link to "/usr/share/dict/"
$ ls -lgGh s_link ←Check the size of the symbolic link file "s_link"
lrwxrwxrwx. 1 16 Jul 12 22:25 s_link -> /usr/share/dict/ ←its symbolic link only occupies 16 bytes

In the example above, if you read or write the symbolic link file "s_link," it is equivalent to reading or writing the source file "/usr/share/dict." However, the file size of the symbolic link is much smaller, only 16 bytes. If you pay close attention, you may notice that the size of the symbolic link file is exactly the same as the number of characters in the path. Therefore, the symbolic link file actually only records the path of the source file. If the "ln" command is used with a relative path, it may cause extension issues. Let's conduct an experiment to further understand this.

Example: (Experiment with symbolic link relative/absolute paths)
$ cd ~ ←cd to the home directory to experiment
$ echo '12345' > source ←Create a file "source" with content "12345"
$ ln -sf source s_link ←Creating a symbolic link file "s_link" linking to the file "source"
$ cat s_link ←Verify that the content of the soft link file "s_link" is the same as "source"
12345
$ mv s_link /tmp ← Move the soft link file "s_link" to the directory /tmp
$ cat /tmp/s_link ←Verify the content of the soft link file "s_link"
cat: /tmp/s_link: No such file or directory ←No file found

$ ln -sf ~/source s_link ←Try the above steps again with an absolute path
$ mv -f s_link /tmp
$ cat /tmp/s_link ←Verify
12345 ←If you use an absolute path, there will be no problem moving the soft link file to another directory
$ rm ~/source ←remove the source file
$ cat /tmp/s_link ←Verify that the source file is gone, what will happen to the soft link file ?
cat: /tmp/s_link: No such file or directory ← No file found

Based on the above experiment, it is evident that using absolute paths is preferable when working with symbolic links. Additionally, if the source file of a symbolic link is accidentally deleted, the link becomes invalid.

Symbolic links can be created not only for files but also for directories. Furthermore, they can span across different file systems. This means that you can create a symbolic link that points to a file or directory located in a different file system or partition.

Example: (symbolic link to directory)
$ ln -s /etc s_link2dir ←Create a symbolic link file "s_link2dir" to link to the directory "/etc"
$ ls -lgG s_link2dir ←Use the command ls to see if "s_link2dir" is linked to the directory "/etc"
lrwxrwxrwx 1 4 2011-09-13 16:49 s_link_dir -> /etc
$ cd s_link2dir ←Check if you can enter the symbolic link directory

we have experimented with symbolic links, now let's move on to testing hard links

Example:
$ cp /etc/services /tmp ←Copy /etc/services to the /tmp directory to prepare as the source file for the experiment
$ ln /tmp/services h_link ←Create a hard link "h_link" to the source file "/tmp/services "(ln no option is hard link)
$ ls -li /tmp/services h_link ←List the two files and see
1880233 -rw-r--r-- 2 aaa aaa 362047 2011-09-13 17:09 h_link ←The two files are the same except for the file name
(The green text above intentionally marks the inode number, while the red text represents the link coun)

1880233 -rw-r--r-- 2 aaa aaa 362047 2011-09-13 17:09 /tmp/services

$ rm /tmp/services ←If you delete the source file, let's observe the behavior of hard links
$ ls -li h_link
1880233 -rw-r--r-- 1 aaa aaa 362047 2011-09-13 17:09 h_link ←When the source file is deleted, it does not affect the hard link files themselves. However, the link count for the inode of the source file decreases to 1
$ cat h_link ←Let's verify whether the hard link file can still be read even when the source file is deleted.

In a file system like Linux ext2/ext3, each file has a unique inode number. If two files have the same inode number, they are considered the same file. When a hard link is created, the link count of the associated inode increases by one. As mentioned before, a hard link acts as both the original file and a duplicate, so as long as one hard link exists, the data remains secure. Hard links provide better security in terms of data availability.

However, hard links have some limitations. They cannot be created for directories, and they cannot span across different file systems or partitions. These restrictions prevent hard links from being used in scenarios where linking directories or files across file systems is necessary.



^ back on top ^

cp : File Copy
The Linux file copying command, cp (copy), has a simple basic usage. Essentially, it is used as cp source_file destination_file or cp source_file1 source_file2 ... destination_directory (to copy one or multiple files to a directory) or cp -r source_directory destination_directory (to copy a source directory to a destination directory recursively).

Here are some further usage options and explanations:

Syntax:cp [-otpiton][--option] source traget
Command name/Function/Command use Options Function
cp/
file copy/
Any
-a 完全複製(包含其檔案擁有者,連結,目錄,時間)同等 -dpR (常用於備份)

complete copy of files and directories, preserving their attributes, ownership, links, and timestamps. It is equivalent to using the options "-dpR", which are commonly used for backup purposes.
-b If the target file already exists, it will automatically back up the existing file first (add "~" at the end of the backup file)
-d If the source is a symbolic link file, the copied file is also a symbolic link file
-f If the destination file already exists, overwrite the old file directly without being prompted
-i If the destination file already exists, you will be prompted to confirm before overwriting the old file
-l Used to create hard links instead of copying files
-p Copy files while preserving their ownership, timestamps, and permissions
-r Recursive copy, copy all files and subdirectories under the source directory together
-R Same as option "-r"
-s Create symbolic links instead of copying files
-S字串 Same as "-b" but can specify backup file suffix string
-u Update (only copy the source file whose mtime time is newer than the destination file's mtime time or the destination file does not have a file)
-v Show copy process
--help Displays the command's built-in help and usage information

Example:
$ cp file1 file2 ←copy file1 to file2
$ cp /dev/null file1 ←Empty file1 contents
$ cp /dir/file ./ ←Copy archive /dir/file to working director
$ cp file ../ ←Copy a file to the parent directory of the current working directory
$ cp -r dir1/ dir2/ ←Copy all files and subdirectories, including their contents, from the source directory dir1 to the directory dir2
$ cp file1 file2 file3 dir ←If there are multiple source files and the destination must be a directory, this example copies file1 to file3 into the directory dir
$ cp -b /dir/file ./ ←If the file already exists in the current working directory, it will be backed up as file~ before performing the copy operation
$ cp -S'_backuped' file1 file2 ←If file2 already exists, it will be backed up as file2_backuped before performing the copy operation (specifying the backup file suffix)
$ cp -auv dir1/ dir2/ ←Update directory dir2 (source: dir1) and display the progress of the updates (commonly used for backup purposes)
$ cp -s file1 file2 ←Equivalent to the command "ln -s file1 file2", creates a symbolic link file2
$ cp -i file1 file2 ←Copy file1 to file2, but if file2 already exists, it will prompt for confirmation before overwriting the existing file

In Linux, the cp command has a feature where, if permissions allow, regardless of the ownership and group of the source file, the copied file will have the ownership and group set to the user performing the copy operation. This is done to allow the operator full control over the copied file. If you want to preserve the original attributes, you can use cp -a or cp -p.

Example:
$ ls -l /etc/fstab ←Is used to view the ownership and group of the file /etc/fstab
-rw-r--r-- 1 root root 608 2011-09-16 00:21 /etc/fstab ←Both the ownership and group of the file are currently set to "root."
$ cp /etc/fstab ./ ←Copy /etc/fstab to the working directory
$ ls -l fstab ←Is used to view the ownership and group of the file "fstab"
-rw-r--r-- 1 aaa aaa 608 2012-02-10 12:50 fstab ←owner/group changes to creator

In the previous example, even if you use the option cp -p, it will not be able to copy the ownership and group "root" because of insufficient permissions. Conversely, if you use cp -p while logged in as root, you have unlimited privileges and can copy files with any ownership and group.

Furthermore, when using the cp command, if the source file is a symbolic link, the destination file will no longer be a symbolic link (it will be a regular file copied from the source). To preserve the symbolic link in the destination file, you can use the "-d" option. The "-a" option is equivalent to combining the functionality of "-d," "-p," and "-R," providing a complete copy operation. It is often used for file backups.

If you use cp for regular backups but have large and numerous files, copying each file can be time-consuming. By using the "-u" option, you can save a significant amount of time. This option allows the command to determine whether a file has been updated or if there are any new files based on the modification time (mtime), thus deciding whether to copy the file.

Additionally, it is recommended to develop good command operation habits. When working with directories, it is advisable to append a "/" at the end of the directory name to differentiate it as a directory. For example, when copying directory "dir1" to directory "dir2," you can use cp -r dir1 dir2, but using "cp -r dir1/ dir2/ makes it clearer that you are working with directories. In practice, the standard notation for directories includes the trailing "/", although it is commonly omitted by most people. However, in certain applications, it is necessary to explicitly include the "/"; for example, ls -d */ is used to list directories in the current working directory without displaying files.




^ back on top ^

rm : File Delete
The Linux command for deleting files is rm (remove). The basic usage is to specify the files to be deleted like this: rm file1 file2 fileN. Here are some advanced usage options

Syntax:cp [-otpiton][--option] file/directory
Command name/Function/Command use Options Functioin
rm/
remove file/
Any
-f Delete files without asking
-i Ask to ask before deleting files
-r Recursive delete, delete all files and subdirectories under the source directory
-R Same as option "-r"
-v show delete process
--help Displays the command's built-in help and usage information

rm 刪除檔案指令也可刪除目錄,如用 rm -fr dir/ 來刪除目錄連問都不問就把整個目錄都殺光。所以 rm 是很危險的指令,所以建議殺目錄用專屬的殺目錄指令 rmdir 比較安全。
The rm command, used for deleting files, can also delete directories. For example, using rm -fr dir/ will delete the entire directory "dir" and its contents without any prompts, effectively erasing the entire directory. Therefore, rm is considered a potentially dangerous command. It is advisable to use the dedicated rmdir command for deleting directories as it is safer.

例:
$ rm file ←Delete file file
$ rm 'file 1' ←Delete the file named "file 1". If a file name contains spaces or special characters, it is important to enclose the filename within quotation marks
$ rm file1 file2 file3 ←Delete multiple files at once
$ rm -ri dir/ ← Delete a directory and all its files, with a confirmation prompt for each file
$ rm -rf dir ←Is used to delete the directory and all files within it without any prompts.
$ rm ./-10degree ←Delete the file "-10degree"

In the last example, it is important to be cautious. If a file has a peculiar character as the first character, such as in the example "-10degree," the hyphen (-) may be mistakenly interpreted as an option by the command. To address this issue, you can use "./" to represent the current working directory and separate it from the filename. However, it is generally not recommended to use overly unique or unconventional filenames, as it can lead to confusion and potential issues.

^ back on top ^

mv : File Move
The file movement command mv (move) and the file copy command cp have similar usage and options. The only difference is that mv deletes the source file after moving it. Additionally, mv does not have the "-r" or "-R" options for recursive directory movement. If you use mv to move a directory, it automatically includes all files and subdirectories within the directory. The usage of mv is as follows:

語法:mv [-otpiton][--option] source target
Command name/Function/Command use Options Function
mv/
file move/
Any
-b When the destination file already exists, will automatically create a backup of the existing file by appending a tilde (~) to its filename
-f Not prompt for confirmation and will directly overwrite the existing file with the file being moved
-i Will prompt for confirmation before overwriting the existing file
-STRING Same as "-b" but can specify backup file suffix string
-u Move only updated files (move files only if the source file's modification time (mtime) is newer than the destination file's mtime or if the destination file does not exist)
-v It will show the verbose output
--help Displays the command's built-in help and usage information

例:
$ mv file1 file2 ←Move "file1" to "file2", this example is equivalent to renaming file1 to file2
$ mv dir1/ dir2/ ← Move the directory "dir1" (including all files and subdirectories within it) to the directory "dir2". This operation is equivalent to renaming the directory
$ mv -i file ../ ←Move the file named "file" to its parent directory. If the destination file exists, prompt for confirmation before proceeding with the move
$ mv -b file dir/ ←Move the file named "file" to the directory "dir". If the destination file exists, create a backup (by appending a tilde (~) to the backup file's name) before overwriting it

The first example mv file1 file2 is also one of the main usages of mv for renaming.

^ back on top ^

"\" : Escape Character
The escape character "\" is used to temporarily remove the special functionality or alter the functionality of certain characters (such as (/), ,({),(?),('),(") etc.) due to syntactical conflicts. For example, if you want to display the string "I'm happy and I'm a student" using the echo command, writing it as echo I'm happy and I'm a student would result in an error output. This is because the single or double quotation marks('), or (") are used to enclose the string. To output it correctly, you can use the escape character "/" to temporarily remove the original functionality of the quotation marks, like this: echo I\'m happy and I\'m a student.

Example: (Escaping the special character's original functionality temporarily)
$ echo > "fileA" ←Creates a file named "fileA"
$ echo > ""fileB"" ← Creates a file named ""fileB""
$ ls ←Confirming the files
fileA      fileB ←The quotation marks around the file names disappeared?
$ echo > \"fileC\" ←Using the "\" to create a file named "fileC" with quotation marks
$ ls
fileA      fileB      "fileC" ← "fileC" is displayed with quotation marks

$ rm \"fileC\" ←Using the escape character to operate on a file with syntactical conflicts


Example: (Changing functionality)
echo -e 'I\x27m a student' ←Using the escape character to change the functionality to ASCII code (ASCII code 27HEX represents a single quotation mark)
I'm a student

\ls  ←Adding an escape character before the command represents "remove the alias" (in most distributions, "ls" is an alias for 'ls --color=auto', so removing the alias will prevent the colored output))


^ back on top ^



 


    [註]參考 http://www.farhadsaberi.com/linux_freebsd/2010/12/hard-link-soft-symbolic-links.html