Sparse enabled 'dd‘ test

本文介绍了一段bash脚本,用于验证使用'dd'命令生成的文件是否为稀疏文件。通过比较实际大小和显式大小,确保文件的有效性。
To Check if the 'dd' command is using Sparse :

#!/bin/bash
# set -x

file_name="tttt.img"

`dd if=/dev/zero of=$file_name bs=1024 count=10 seek=10`
 sp_file_size=`du -h $file_name | awk '{print $1}'`
      sp_file_size_app=`du -h --apparent-size $file_name | awk '{print $1}'`

      echo "   Comparing the actual & apparent file sizes ..."
      if [ $sp_file_size == $sp_file_size_app ]; then
          echo "   Failed to create Sparse file: $file_name"
          return 1
      else
          echo "   Sparse file in deed sparsed... "
      fi





PHP logo PHP Version 5.6.40 System Linux yfw.szrengjing.com 4.18.0-348.7.1.el8_5.x86_64 #1 SMP Wed Dec 22 13:25:12 UTC 2021 x86_64 Build Date May 12 2020 15:26:41 Configure Command './configure' '--prefix=/www/server/php/56' '--with-config-file-path=/www/server/php/56/etc' '--enable-fpm' '--with-fpm-user=www' '--with-fpm-group=www' '--with-mysql=mysqlnd' '--with-mysqli=mysqlnd' '--with-pdo-mysql=mysqlnd' '--with-iconv-dir' '--with-freetype-dir=/usr/local/freetype' '--with-jpeg-dir' '--with-png-dir' '--with-zlib' '--with-libxml-dir=/usr' '--enable-xml' '--disable-rpath' '--enable-bcmath' '--enable-shmop' '--enable-sysvsem' '--enable-inline-optimization' '--with-curl=/usr/local/curl' '--enable-mbregex' '--enable-mbstring' '--with-mcrypt' '--enable-ftp' '--with-gd' '--enable-gd-native-ttf' '--with-openssl=/usr/local/openssl' '--with-mhash' '--enable-pcntl' '--enable-sockets' '--with-xmlrpc' '--enable-zip' '--enable-soap' '--with-gettext' '--disable-fileinfo' '--enable-opcache' '--enable-intl' Server API FPM/FastCGI Virtual Directory Support disabled Configuration File (php.ini) Path /www/server/php/56/etc Loaded Configuration File /www/server/php/56/etc/php.ini Scan this dir for additional .ini files (none) Additional .ini files parsed (none) PHP API 20131106 PHP Extension 20131226 Zend Extension 220131226 Zend Extension Build API220131226,NTS PHP Extension Build API20131226,NTS Debug Build no Thread Safety disabled Zend Signal Handling disabled Zend Memory Manager enabled Zend Multibyte Support provided by mbstring IPv6 Support enabled DTrace Support disabled Registered PHP Streams https, ftps, compress.zlib, php, file, glob, data, http, ftp, phar, zip, smb, compress.zstd Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2 Registered Stream Filters zlib.*, convert.iconv.*, mcrypt.*, mdecrypt.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk Zend logoThis program makes use of the Zend Scripting Language Engine: Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies with Zend Guard Loader v3.3, Copyright (c) 1998-2014, by Zend Technologies Configuration bcmath BCMath support enabled Directive Local Value Master Value bcmath.scale 0 0 cgi-fcgi php-fpm active Directive Local Value Master Value cgi.discard_path 0 0 cgi.fix_pathinfo 1 1 cgi.force_redirect 1 1 cgi.nph 0 0 cgi.redirect_status_env no value no value cgi.rfc2616_headers 0 0 fastcgi.error_header no value no value fastcgi.logging 1 1 fpm.config no value no value Core PHP Version 5.6.40 Directive Local Value Master Value allow_url_fopen On On allow_url_include Off Off always_populate_raw_post_data 0 0 arg_separator.input & & arg_separator.output & & asp_tags Off Off auto_append_file no value no value auto_globals_jit On On auto_prepend_file no value no value browscap no value no value default_charset UTF-8 UTF-8 default_mimetype text/html text/html disable_classes no value no value disable_functions passthru,proc_open,putenv,exec,system,chroot,chgrp,chown,shell_exec,popen,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,proc_open,putenv,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv passthru,proc_open,putenv,exec,system,chroot,chgrp,chown,shell_exec,popen,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,proc_open,putenv,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv display_errors Off Off display_startup_errors Off Off doc_root no value no value docref_ext no value no value docref_root no value no value enable_dl Off Off enable_post_data_reading On On error_append_string no value no value error_log no value no value error_prepend_string no value no value error_reporting 32759 32759 exit_on_timeout Off Off expose_php Off Off extension_dir /www/server/php/56/lib/php/extensions/no-debug-non-zts-20131226 /www/server/php/56/lib/php/extensions/no-debug-non-zts-20131226 file_uploads On On highlight.comment #FF8000 #FF8000 highlight.default #0000BB #0000BB highlight.html #000000 #000000 highlight.keyword #007700 #007700 highlight.string #DD0000 #DD0000 html_errors On On ignore_repeated_errors Off Off ignore_repeated_source Off Off ignore_user_abort Off Off implicit_flush Off Off include_path .:/www/server/php/56/lib/php .:/www/server/php/56/lib/php input_encoding no value no value internal_encoding no value no value log_errors On On log_errors_max_len 1024 1024 mail.add_x_header On On mail.force_extra_parameters no value no value mail.log no value no value max_execution_time 300 300 max_file_uploads 20 20 max_input_nesting_level 64 64 max_input_time 60 60 max_input_vars 1000 1000 memory_limit 256M 256M open_basedir /www/wwwroot/szrengjing.com/:/tmp/ no value output_buffering 4096 4096 output_encoding no value no value output_handler no value no value post_max_size 100M 100M precision 14 14 realpath_cache_size 16K 16K realpath_cache_ttl 120 120 register_argc_argv Off Off report_memleaks On On report_zend_debug On On request_order GP GP sendmail_from no value no value sendmail_path /usr/sbin/sendmail -t -i /usr/sbin/sendmail -t -i serialize_precision 17 17 short_open_tag On On SMTP localhost localhost smtp_port 25 25 sql.safe_mode Off Off sys_temp_dir no value no value track_errors Off Off unserialize_callback_func no value no value upload_max_filesize 100M 100M upload_tmp_dir no value no value user_dir no value no value user_ini.cache_ttl 300 300 user_ini.filename .user.ini .user.ini variables_order GPCS GPCS xmlrpc_error_number 0 0 xmlrpc_errors Off Off zend.detect_unicode On On zend.enable_gc On On zend.multibyte Off Off zend.script_encoding no value no value ctype ctype functions enabled curl cURL support enabled cURL Information 7.70.0 Age 6 Features AsynchDNS Yes CharConv No Debug No GSS-Negotiate No IDN No IPv6 Yes krb4 No Largefile Yes libz Yes NTLM Yes NTLMWB Yes SPNEGO No SSL Yes SSPI No TLS-SRP Yes Protocols dict, file, ftp, ftps, gopher, http, https, imap, imaps, pop3, pop3s, rtsp, smb, smbs, smtp, smtps, telnet, tftp Host x86_64-pc-linux-gnu SSL Version OpenSSL/1.0.2u ZLib Version 1.2.11 date date/time support enabled "Olson" Timezone Database Version 2016.10 Timezone Database internal Default timezone PRC Directive Local Value Master Value date.default_latitude 31.7667 31.7667 date.default_longitude 35.2333 35.2333 date.sunrise_zenith 90.583333 90.583333 date.sunset_zenith 90.583333 90.583333 date.timezone PRC PRC dom DOM/XML enabled DOM/XML API Version 20031129 libxml Version 2.9.7 HTML Support enabled XPath Support enabled XPointer Support enabled Schema Support enabled RelaxNG Support enabled ereg Regex Library Bundled library enabled event Event support enabled Sockets support enabled Debug support disabled Extra functionality support including HTTP, DNS, and RPC enabled OpenSSL support enabled Thread safety support disabled Extension version 3.0.8 libevent2 headers version 2.1.8-stable exif EXIF Support enabled EXIF Version 1.4 $Id: 1c8772f76be691b7b3f77ca31eb788a2abbcefe5 $ Supported EXIF Version 0220 Supported filetypes JPEG,TIFF Directive Local Value Master Value exif.decode_jis_intel JIS JIS exif.decode_jis_motorola JIS JIS exif.decode_unicode_intel UCS-2LE UCS-2LE exif.decode_unicode_motorola UCS-2BE UCS-2BE exif.encode_jis no value no value exif.encode_unicode ISO-8859-15 ISO-8859-15 fileinfo fileinfo support enabled version 1.0.5 libmagic 517 filter Input Validation and Filtering enabled Revision $Id: 5b79667bd9a68977a9b4f7505223a8e216e04908 $ Directive Local Value Master Value filter.default unsafe_raw unsafe_raw filter.default_flags no value no value ftp FTP support enabled gd GD Support enabled GD Version bundled (2.1.0 compatible) FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.9.1 GIF Read Support enabled GIF Create Support enabled JPEG Support enabled libJPEG Version 6b PNG Support enabled libPNG Version 1.6.34 WBMP Support enabled XBM Support enabled Directive Local Value Master Value gd.jpeg_ignore_warning 0 0 gettext GetText Support enabled hash hash support enabled Hashing Engines md2 md4 md5 sha1 sha224 sha256 sha384 sha512 ripemd128 ripemd160 ripemd256 ripemd320 whirlpool tiger128,3 tiger160,3 tiger192,3 tiger128,4 tiger160,4 tiger192,4 snefru snefru256 gost gost-crypto adler32 crc32 crc32b fnv132 fnv1a32 fnv164 fnv1a64 joaat haval128,3 haval160,3 haval192,3 haval224,3 haval256,3 haval128,4 haval160,4 haval192,4 haval224,4 haval256,4 haval128,5 haval160,5 haval192,5 haval224,5 haval256,5 iconv iconv support enabled iconv implementation glibc iconv library version 2.28 Directive Local Value Master Value iconv.input_encoding no value no value iconv.internal_encoding no value no value iconv.output_encoding no value no value imagick imagick module enabled imagick module version 3.4.4 imagick classes Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel Imagick compiled with ImageMagick version ImageMagick 7.1.0-16 Q16-HDRI x86_64 2021-11-21 https://imagemagick.org Imagick using ImageMagick library version ImageMagick 7.1.0-16 Q16-HDRI x86_64 2021-11-21 https://imagemagick.org ImageMagick copyright (C) 1999-2021 ImageMagick Studio LLC ImageMagick release date 2021-11-21 ImageMagick number of supported formats: 249 ImageMagick supported formats 3FR, 3G2, 3GP, A, AAI, AI, APNG, ART, ARW, ASHLAR, AVI, AVS, B, BGR, BGRA, BGRO, BMP, BMP2, BMP3, BRF, C, CAL, CALS, CANVAS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CR3, CRW, CUBE, CUR, CUT, DATA, DCM, DCR, DCRAW, DCX, DDS, DFONT, DNG, DPX, DXT1, DXT5, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, ERF, FARBFELD, FAX, FF, FILE, FITS, FL32, FLV, FRACTAL, FTP, FTS, G, G3, G4, GIF, GIF87, GRADIENT, GRAY, GRAYA, GROUP4, HALD, HDR, HISTOGRAM, HRZ, HTM, HTML, HTTP, HTTPS, ICB, ICO, ICON, IIQ, INFO, INLINE, IPL, ISOBRL, ISOBRL6, JNG, JNX, JPE, JPEG, JPG, JPS, JSON, K, K25, KDC, LABEL, M, M2V, M4V, MAC, MAP, MASK, MAT, MATTE, MEF, MIFF, MKV, MNG, MONO, MOV, MP4, MPC, MPEG, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NRW, NULL, O, ORA, ORF, OTB, OTF, PAL, PALM, PAM, PANGO, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PES, PFA, PFB, PFM, PGM, PGX, PHM, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8, PNM, POCKETMOD, PPM, PS, PS2, PS3, PSB, PSD, PTIF, PWP, R, RADIAL-GRADIENT, RAF, RAS, RAW, RGB, RGB565, RGBA, RGBO, RGF, RLA, RLE, RMF, RW2, SCR, SCREENSHOT, SCT, SFW, SGI, SHTML, SIX, SIXEL, SPARSE-COLOR, SR2, SRF, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TM2, TTC, TTF, TXT, UBRL, UBRL6, UIL, UYVY, VDA, VICAR, VID, VIFF, VIPS, VST, WBMP, WEBM, WEBP, WMV, WPG, X, X3F, XBM, XC, XCF, XPM, XPS, XV, XWD, Y, YAML, YCbCr, YCbCrA, YUV Directive Local Value Master Value imagick.locale_fix 0 0 imagick.progress_monitor 0 0 imagick.skip_version_check 0 0 intl Internationalization support enabled version 1.1.0 ICU version 60.3 ICU Data version 60.3 Directive Local Value Master Value intl.default_locale no value no value intl.error_level 0 0 intl.use_exceptions 0 0 json json support enabled json version 1.2.1 libsmbclient Version 1.0.6 libxml libXML support active libXML Compiled Version 2.9.7 libXML Loaded Version 20907 libXML streams enabled mbstring Multibyte Support enabled Multibyte string engine libmbfl HTTP input encoding translation disabled libmbfl version 1.3.2 mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1. Multibyte (japanese) regex support enabled Multibyte regex (oniguruma) backtrack check On Multibyte regex (oniguruma) version 5.9.5 Directive Local Value Master Value mbstring.detect_order no value no value mbstring.encoding_translation Off Off mbstring.func_overload 0 0 mbstring.http_input no value no value mbstring.http_output no value no value mbstring.http_output_conv_mimetypes ^(text/|application/xhtml\+xml) ^(text/|application/xhtml\+xml) mbstring.internal_encoding no value no value mbstring.language neutral neutral mbstring.strict_detection Off Off mbstring.substitute_character no value no value mcrypt mcrypt support enabled mcrypt_filter support enabled Version 2.5.8 Api No 20021217 Supported ciphers cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish enigma rc2 tripledes Supported modes cbc cfb ctr ecb ncfb nofb ofb stream Directive Local Value Master Value mcrypt.algorithms_dir no value no value mcrypt.modes_dir no value no value memcached memcached support enabled Version 2.2.0 libmemcached version 1.0.18 SASL support yes Session support yes igbinary support no json support no msgpack support no Directive Local Value Master Value memcached.compression_factor 1.3 1.3 memcached.compression_threshold 2000 2000 memcached.compression_type fastlz fastlz memcached.serializer php php memcached.sess_binary 0 0 memcached.sess_connect_timeout 1000 1000 memcached.sess_consistent_hash 0 0 memcached.sess_lock_expire 0 0 memcached.sess_lock_max_wait 0 0 memcached.sess_lock_wait 150000 150000 memcached.sess_locking 1 1 memcached.sess_number_of_replicas 0 0 memcached.sess_prefix memc.sess.key. memc.sess.key. memcached.sess_randomize_replica_read 0 0 memcached.sess_remove_failed 0 0 memcached.sess_sasl_password no value no value memcached.sess_sasl_username no value no value memcached.store_retry_count 2 2 memcached.use_sasl 0 0 mhash MHASH support Enabled MHASH API Version Emulated Support mysql MySQL Support enabled Active Persistent Links 0 Active Links 0 Client API version mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $ Directive Local Value Master Value mysql.allow_local_infile On On mysql.allow_persistent On On mysql.connect_timeout 60 60 mysql.default_host no value no value mysql.default_password no value no value mysql.default_port no value no value mysql.default_socket no value no value mysql.default_user no value no value mysql.max_links Unlimited Unlimited mysql.max_persistent Unlimited Unlimited mysql.trace_mode Off Off mysqli MysqlI Support enabled Client API library version mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $ Active Persistent Links 0 Inactive Persistent Links 0 Active Links 0 Directive Local Value Master Value mysqli.allow_local_infile On On mysqli.allow_persistent On On mysqli.default_host no value no value mysqli.default_port 3306 3306 mysqli.default_pw no value no value mysqli.default_socket no value no value mysqli.default_user no value no value mysqli.max_links Unlimited Unlimited mysqli.max_persistent Unlimited Unlimited mysqli.reconnect Off Off mysqli.rollback_on_cached_plink Off Off mysqlnd mysqlnd enabled Version mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $ Compression supported core SSL supported extended SSL supported Command buffer size 4096 Read buffer size 32768 Read timeout 31536000 Collecting statistics Yes Collecting memory statistics No Tracing n/a Loaded plugins mysqlnd,debug_trace,auth_plugin_mysql_native_password,auth_plugin_mysql_clear_password,auth_plugin_sha256_password API Extensions pdo_mysql,mysqli,mysql mysqlnd statistics bytes_sent 90861536 bytes_received 394494535 packets_sent 1356160 packets_received 6262207 protocol_overhead_in 25048828 protocol_overhead_out 5424640 bytes_received_ok_packet 0 bytes_received_eof_packet 0 bytes_received_rset_header_packet 5709357 bytes_received_rset_field_meta_packet 0 bytes_received_rset_row_packet 3386087 bytes_received_prepare_response_packet 153977064 bytes_received_change_user_packet 227294569 packets_sent_command 665079 packets_received_ok 0 packets_received_eof 0 packets_received_rset_header 634373 packets_received_rset_field_meta 0 packets_received_rset_row 645578 packets_received_prepare_response 2273832 packets_received_change_user 2682422 result_set_queries 627873 non_result_set_queries 17703 no_index_used 47526 bad_index_used 0 slow_queries 0 buffered_sets 627873 unbuffered_sets 0 ps_buffered_sets 0 ps_unbuffered_sets 0 flushed_normal_sets 0 flushed_ps_sets 0 ps_prepared_never_executed 0 ps_prepared_once_executed 0 rows_fetched_from_server_normal 2054549 rows_fetched_from_server_ps 0 rows_buffered_from_client_normal 2054549 rows_buffered_from_client_ps 0 rows_fetched_from_client_normal_buffered 2053367 rows_fetched_from_client_normal_unbuffered 0 rows_fetched_from_client_ps_buffered 0 rows_fetched_from_client_ps_unbuffered 0 rows_fetched_from_client_ps_cursor 0
最新发布
11-10
<think>我们正在讨论`dd`命令的`conv=sparse`选项。根据引用[5],`dd`命令的`bs`选项可以同时设置输入和输出的块大小。而`conv`选项用于指定转换规则,其中`sparse`是其中一个选项。 用户询问的是`conv=sparse`选项的用法。根据`dd`的文档,`conv=sparse`选项用于在写入输出文件时尝试检测并跳过全零的块,从而在输出文件中创建稀疏文件(即文件系统会优化存储,不实际占用全零块的空间)。这在处理大文件且包含大量零块时特别有用,可以节省磁盘空间。 具体用法示例: ```bash dd if=inputfile of=outputfile conv=sparse ``` 注意: 1. 使用`conv=sparse`时,通常需要配合`bs`选项设置块大小,因为检测零块是基于每个块进行的。例如,设置`bs=4M`,则每次读取4MB,如果这4MB都是零,则不会实际写入磁盘(而是创建一个“空洞”)。 2. 这个选项只影响输出文件,不会改变输入数据的读取。 引用[4]中有一个使用`dd`的例子,但没有使用`conv=sparse`。我们可以参考其格式,添加`conv=sparse`。 例如,将ISO镜像写入USB设备并希望节省空间(如果ISO中有大量零区域): ```bash dd if=file.iso of=/dev/sdb bs=4M conv=sparse ``` 但是注意,对于设备文件(如`/dev/sdb`),文件系统可能不支持稀疏文件,所以在这种情况下可能无效。`conv=sparse`主要针对普通文件系统上的文件。 另外,引用[1]和[3]没有直接提到`conv=sparse`,但提供了`dd`命令的一般语法。引用[5]提到了`bs`选项,但没有具体说明`conv=sparse`。 因此,我们总结: - `conv=sparse`用于创建稀疏文件,节省磁盘空间。 - 适用于输出是普通文件(而不是块设备)的情况。 - 需要配合合适的块大小(`bs`)使用,以便有效检测零块。 相关问题: 1. 什么是稀疏文件?在Linux中如何创建? 2. 除了`conv=sparse`,`dd`命令还有哪些常用的转换选项? 3. 如何检查一个文件是否是稀疏文件?</think>### `dd` 命令的 `conv=sparse` 选项详解 `conv=sparse` 是 `dd` 命令中用于优化存储空间的选项,主要功能是**跳过输出文件中的全零块**,从而创建稀疏文件(sparse file)。当写入大量连续零数据时,该选项可显著减少磁盘占用。 #### 工作原理 1. **检测零块**: `dd` 在读取输入数据时,会检测当前块是否全为零(根据 `bs` 或 `obs` 指定的块大小)。 2. **跳过写入**: 若块全为零,则不在磁盘上分配物理空间,而是通过文件系统的"空洞"(hole)机制记录文件逻辑长度。 3. **仅写入非零数据**: 仅当块包含非零数据时,才实际执行磁盘写入操作。 #### 基本语法 ```bash dd if=输入文件 of=输出文件 conv=sparse [其他选项] ``` #### 关键参数说明 - **`bs=BYTES`**: 同时设置读写块大小(覆盖 `ibs` 和 `obs`)。建议显式指定以控制检测粒度(如 `bs=1M`)[^5]。 - **`count=N`**: 限制复制的块数量(可选)。 - **`seek=N`**: 在输出文件开头跳过指定块数(用于创建带空洞的文件)。 --- ### 典型应用场景 #### 1. 创建稀疏磁盘镜像 ```bash # 创建 10GB 的镜像文件,实际仅写入元数据(秒级完成) dd if=/dev/zero of=sparse.img bs=1M count=0 seek=10240 conv=sparse ``` - **效果**: 文件逻辑大小为 10GB,但磁盘占用接近 0(仅存储元数据)。 - **验证**: ```bash ls -lh sparse.img # 显示逻辑大小(如 10G) du -h sparse.img # 显示实际磁盘占用(如 4.0K) ``` #### 2. 克隆含空洞的分区 ```bash # 克隆分区到镜像文件,跳过全零块 dd if=/dev/mmcblk0p1 of=backup.img bs=4M conv=sparse ``` - **优势**: 若分区中有未使用空间(全零),生成的 `backup.img` 将远小于分区原始大小[^4]。 #### 3. 安全擦除敏感数据 ```bash # 用随机数据覆盖非零区域,跳过全零块(避免无谓写入) dd if=/dev/urandom of=file.bin conv=sparse,notrunc ``` - **注意**: 需配合 `notrunc` 防止文件截断。 --- ### 注意事项 1. **文件系统支持**: 仅支持稀疏文件的文件系统有效(如 `ext4`、`XFS`、`NTFS`)。`FAT32` 等不支持。 2. **块大小影响效率**: `bs` 值过小会增加检测开销;过大可能降低空间节省率。建议根据数据特征调整(常用 `1M`/`4M`)[^5]。 3. **与设备文件的兼容性**: 输出到块设备(如 `/dev/sdb`)时,`conv=sparse` **无效**,因为设备文件不支持"空洞"[^2]。 4. **数据完整性验证**: 稀疏文件可能导致 `md5sum` 校验失败(逻辑长度相同但物理存储不同),建议用 `cmp` 或 `sha256sum` 对比。 --- ### 示例演示 #### 场景:克隆一个含 50% 零块的文件 ```bash # 创建测试文件 (1GB 大小,50% 随机数据 + 50% 零块) dd if=<(head -c 500M /dev/urandom; head -c 500M /dev/zero) of=source.bin bs=1M # 传统克隆 (磁盘占用 1GB) dd if=source.bin of=full_copy.bin bs=1M # 稀疏克隆 (磁盘占用约 500MB) dd if=source.bin of=sparse_copy.bin bs=1M conv=sparse # 检查结果 du -h *.bin # 对比 full_copy.bin (1G) 和 sparse_copy.bin (500M) ``` --- ### 相关问题 1. 如何检查一个文件是否为稀疏文件? 2. `dd` 的 `conv=sparse` 和文件系统的透明压缩(如 Btrfs/ZFS)有何优劣? 3. 在哪些场景下使用 `conv=sparse` 可能导致数据风险? 4. 如何将普通文件转换为稀疏文件(无需重写数据)? [^1]: The only options are--helpand--version. SeeCommon options.ddaccepts the following operands, whose syntax was inspired by the DD (data definition) statement of OS/360 JCL. ‘ if=file’ [^2]: dd if=/path/to/file.iso of=/dev/sdb bs=4M && sync: 将 ISO 镜像文件写入到 USB 设备 /dev/sdb,写入完成后执行 sync,确保所有缓存的数据都被写入。 [^4]: root@xyhp:~# qemu-img dd -O qcow2 bs=1m if=/dev/mmcblk0p1 of=COREELEC.qcow2 [^5]: Linux -- dd 命令。`bs=BYTES' Set both input and output block sizes to BYTES. This makes `dd' read and write BYTES per block, overriding any `ibs' and `obs' settings.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值