在 Linux 世界中,dd 命令是一個強大而靈活的工具,最初設計為底層數據操作工具,dd 已經廣泛的應用在與數據管理相關各種任務中,例如:複製、轉換和寫入數據到不同的存儲介質。它處理原始塊級別數據的能力使其成為處理磁盤映像、恢復數據、性能測試的首選解決方案。
在本文中,我們將深入研究 Linux 中 dd 命令的 15 個實際示例,幫助您快速掌握 dd 命令。
1. Copying a file
dd 命令可以用於複製文件,就像 cp 命令一樣,從輸入文件中讀取數據 (if) 並將其寫入輸出文件 (of)
dd if=input.txt of=output.txt
輸入結果如下:
10+0 records in
10+0 records out
5120 bytes (5.1 kB, 5.0 KiB) copied, 0.000939 s, 5.4 MB/s
2. Creating a disk image
你可以使用 dd 命令創建一個完整的磁盤或分區鏡像。這對備份非常有用,因為它備份了整個磁盤或分區,包括其結構和內容。
dd if=/dev/sda of=/path/to/backup/disk_image.img
3. Restoring a disk image
要從鏡像中恢復磁盤或分區,使用 dd 命令將鏡像文件作為輸入目標磁盤或分區作為輸出。
dd if=disk_image.img of=/dev/sda
4. Creating a bootable USB drive
將 ISO 鏡像寫入 USB 驅動器以使其可引導,這對於安裝新的操作系統非常有用。
dd if=linux_distro.iso of=/dev/sdb bs=4M status=progress
5. Securely erasing a disk
使用隨機數據覆蓋磁盤或分區,保證原有數據無法恢復。這在處理存儲設備或準備加密設備時非常有用。
dd if=/dev/urandom of=/dev/sda bs=1M status=progress
6. Cloning a disk
將一個磁盤直接克隆到另一個磁盤,這對於升級存儲設備、在設備間遷移數據或創建備份非常有用。conv=noerror,sync 選項確保跳過任何讀取錯誤,並同步輸出輸入數據。
dd if=/dev/sda of=/dev/sdb bs=64K conv=noerror,sync status=progress
7. Converting uppercase to lowercase
將文本文件內容大寫轉換為小寫。
dd if=input.txt of=output.txt conv=lcase
8. Converting lowercase to uppercase
將文本文件內容小寫轉換為大寫。
dd if=input.txt of=output.txt conv=ucase
9. Extracting a specific portion of a file
提取文件的前 10 MB,這對於分析大文件特定部件是很有用的。
dd if=input_file of=extracted_file bs=1M count=10
10. Creating a fixed-size file filled with zeros
創建一個滿是零的 1 GB 文件。這對於在文件系統上分配空間很有用,測試磁盤性能,或生成假數據。
dd if=/dev/zero of=1GB_file bs=1G count=1
結果如下:
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.17362 s, 914 MB/s
11. Rescuing data from a damaged disk
使用 dd 命令從損壞的磁盤中恢復數據。conv=noerror,sync 選項確保跳過任何讀取錯誤,並同步輸出輸入。
dd if=/dev/sda of=recovered_data.img conv=noerror,sync
12. Benchmarking read performance
通過讀取存儲設備上的數據,並將其丟棄到 /dev/null,以此衡量存儲設備的讀性能。這個測試可以幫助您評估存儲設備的讀取速度。
dd if=/dev/sda of=/dev/null bs=1M count=1024
13. Benchmarking write performance
通過向存儲設備中寫入大量數據來衡量存儲設備的寫性能。conv=fdatasync 選項確保數據被寫入
磁盤命令完成前,提供更準確的寫入速度的測量。
dd if=/dev/zero of=testfile bs=1M count=1024 conv=fdatasync
14. Converting a file from ASCII to EBCDIC
將文本從 ASCII 編碼到 EBCDIC 編碼(這是一種在 IBM 大型機和中型系統上使用的編碼)
dd if=input.txt of=output.txt conv=ebcdic
15. Converting a file from EBCDIC to ASCII
將文本從 EBCDIC 編碼到 ASCII 編碼
dd if=input.txt of=output.txt conv=ascii
我的開源項目
- course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
- course-tencent-cloud(酷瓜雲課堂 - github倉庫)