- 🐧 Альтернативы команды cp на Linux для демонстрации прогресса и скорости
- Как посмотреть прогресс копирования в Linux
- Прогресс команды Linux с помощью progress
- Установка progress
- Смотрим прогресс команды с помощью progress
- Способ второй — создание туннеля
- Выводы
- Progress – A Tiny Tool to Monitor Progress for (cp, mv, dd, tar, etc.) Commands in Linux
- How to Install Progress Viewer in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Linux dd Command Show Progress Copy Bar With Status
- Linux dd Command Show Progress Copy Bar With Status
- How do you monitor the progress of dd?
- Use pv command monitor the progress of dd command and see status
- Examples: Use gnu dd command from coreutils version 8.24 or above only
- How do you monitor the progress of dd on Linux?
- Conclusion
🐧 Альтернативы команды cp на Linux для демонстрации прогресса и скорости
Вы когда-нибудь хотели увидеть скорость и прогресс при копировании файлов с помощью командной строки?
Для копирования файлов, папок и других данных вы, вероятно, использовали бы команду ditto или «cp», если вы знакомы с командной строкой операционных систем Linux или Unix.
Хотя команды ditto и «cp» полезны, иногда использование простой команды «cp» может занять много времени и утомить.
Параметр «-v» (подробный) в команде «cp» может предоставить вам дополнительную информацию о процессе копирования.
Однако недостатком является то, что эта команда не включает индикатор хода процесса копирования.
В Linux есть другие альтернативные команды, которые могут копировать файлы и папки, показывая ход и скорость процесса копирования. Ниже приведены альтернативные команды:
1. Команда rsync
«Rsync» – одна из лучших команд, которая помогает копировать файлы через терминал.
Объем данных, копируемых из удаленного места назначения, уменьшается при использовании этой утилиты.
Он также используется для создания резервных копий данных, копирования данных между компьютерами и зеркалирования.
Команда «rsync» имеет следующий синтаксис:
Использование опции «-av» с «rsync» – самая простая форма этой команды.
Как показано ниже, данная команда скопирует все файлы, находящиеся в «testfolder», в целевую папку с именем «Downloads»:
Источник
Как посмотреть прогресс копирования в Linux
Однако команда dd, как известно, при копировании файла не отображает прогресс бар для пользователя, поэтому непонятно сколько процентов файлов уже скопировано.
В этой статье мы рассмотрим как посмотреть прогресс dd в linux, этот метод подходит не только для dd, но и для всех подобных ей утилит.
Но есть очень простое решение, и даже два. Первое, это утилита Coreutils Viewer или progress (раньше известная как cv). Программа написана на С и ищет выполняемые в данный момент в системе программы такие как: mv, cp, dd, tar, unzip и т д и отображает процент скопированных данных. Второе, более интересное. Мы можем направить данные через туннель pv, который будет считать с какой скоростью они передаются и сколько еще осталось. Рассмотрим сначала первый способ.
Содержание статьи:
Прогресс команды Linux с помощью progress
Установка progress
Эта утилита не поставляется с системой по умолчанию. Но установить ее очень просто, программа есть в официальных репозиториях большинства дистрибутивов. Например, в Ubuntu:
В других дистрибутивах она может быть более старой версии и назваться cv. Также вы можете собрать программу из исходников. Единственная зависимость — библиотека ncurces. В Ubuntu 16.04 ее можно установить такой командой:
В прежних версиях Ubuntu:
В Fedora и CentOS:
Когда удовлетворите зависимости утилиты, выполните следующую команду для загрузки исходников с GitHub:
Затем распакуйте полученный архив:
Измените текущий каталог с помощью cd:
Запустите сборку и установку:
Программа готова к работе.
Смотрим прогресс команды с помощью progress
После завершения установки запустите progress следующей командой:
В результате получится что-то вроде:
Теперь давайте запустим копирование видео из папки на рабочий стол и посмотрим что произойдет:
Команда progress покажет прогресс копирования cp:
Выполним progress еще раз:
Как видите, утилита показывает информацию о прогрессе копирования файла, процент скопированных данных, количество скопированных данных и общий размер файла. Это очень полезно при копировании больших файлов, например, при копировании фильмов или образов дисков. То же самое будет если запустить dd, mv, tar, zip или другую подобную утилиту.
В утилиты есть много полезных опций. Опция -w заставляет программу показывать время, оставшееся до окончания операции:
Если вы хотите видеть упрощенный вывод без дополнительных сообщений используйте опцию -q. И наоборот для показа всех предупреждений и ошибок воспользуйтесь -d. Например, лучше использовать cv со следующими опциями:
Вы можете отслеживать состояние процесса пока он запущен:
Если вы хотите постоянно наблюдать за прогрессом всех команд используйте опцию -М:
Или ее эквивалент:
Очень популярный вот такой вариант:
Также можно посмотреть прогресс linux только нужной программы, например, прогресс загрузки файла в firefox:
Или проверить активность web-сервера:
Способ второй — создание туннеля
То, что мы рассмотрели выше — не единственный способ посмотреть прогресс команды linux. Еще есть утилита pv. Она намного проще и выполняет только одну задачу — считает все данные проходящие через нее. Может читать поток из файла или стандартного ввода.
Поэтому ее можно использовать чтобы посмотреть прогресс выполнения команды в Linux. Например, создадим такой туннель для dd:
Здесь мы выдаем содержимое нужного нам файла на стандартный вывод, передаем утилите pv, а затем она отдает его другой утилите, которая уже выполняет запись в файл. Для cp такое сделать не получиться, но мы можем поступить немного по-другому:
Готово, здесь мы тоже получим прогресс команды копирования.
Выводы
Чтобы использовать всю мощь Linux пользователям часто приходится работать в командной строке. Чаще всего мы смотрим содержимое, копируем файлы, распаковываем архивы. В этой инструкции мы рассмотрели утилиту process, которую можно использовать для просмотра прогресса dd и других системных команд.
Мне всегда было интересно посмотреть прогресс копирования cp для больших файлов. Честно говоря, я часто имею дело с большими файлами при просмотре фильмов на своем ноутбуке.
Источник
Progress – A Tiny Tool to Monitor Progress for (cp, mv, dd, tar, etc.) Commands in Linux
Progress, formerly known as Coreutils Viewer, is a light C command that searches for coreutils basic commands such as cp, mv, tar, dd, gzip/gunzip, cat, grep etc currently being executed on the system and shows the percentage of data copied, it only runs on Linux and Mac OS X operating systems.
Additionally, it also displays important aspects such as estimated time and throughput, and offers users a “top-like” mode.
It utterly scans the /proc filesystem for fascinating commands, and then searches the fd and fdinfo directories to find opened files, seeks positions, and reports status for the extensive files. Importantly, it is a very light tool, and compatible with practically any command.
How to Install Progress Viewer in Linux
Progress requires the ncurses library in order to work, therefore install libncurses before proceeding to install it, by running the appropriate command below:
You can start by cloning or downloading the package files from its Github repo as follows:
Next, move into the progress directory and build it as shown:
After successfully installing it, simply run this tool from your terminal, below we shall walk through a few examples of using Progress on a Linux system.
You can view all the coreutils commands that Progress works with by running it without any options, provided non of the coreutils commands is being executed on the system:
Progress Viewer Commands
To display estimated I/O throughput and estimated remaining time for on going coreutils commands, enable the -w option:
Monitor Progress of Running Commands
Start a heavy command and monitor it using -m option and $! as follows:
Monitor Progress of Linux Commands
In the next example, you can open two or more terminal windows, then run the coreutils commands in one each, and watch their progress using the other terminal window as shown in the image below.
The command below will enable you to monitor all the current and imminent instances of coreutils commands:
For more interesting options, look through the progress man pages or visit https://github.com/Xfennec/progress :
As a concluding remark, this is very useful tool for monitoring the progress of coreutils commands, especially when copying or archiving and compressing heavy files, plus so much more.
If you have installed it successfully, use it and share your experience with us via the comment section below. You can as well provide us some great usage examples where you find it helpful for important everyday system administration tasks and more.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Linux dd Command Show Progress Copy Bar With Status
I am using dd command for block level copy and just found out that there’s no built in way to check the progress. How do I use the Linux or Unix dd command while coping /dev/sda to /deb/sdb and display a progress bar when data goes through a pipe? How do I monitor the progress of dd on Linux?
Tutorial details | |
---|---|
Difficulty level | Intermediate |
Root privileges | Yes |
Requirements | dd and pv |
Est. reading time | 2m |
The dd is a free and open source command-line tool for Linux, and Unix-like operating systems. It is mainly used to convert and copy files. Being a program mainly designed as a filter dd usually does not provide any progress indication. This page shows how to show progress copy bar on Linux operating system using GNU version of the dd command.
Linux dd Command Show Progress Copy Bar With Status
You need to use gnu dd command from coreutils version 8.24 or above to use the following option. The syntax is as follows to show progress copy bar with dd command:
dd if=/path/to/input of=/path/to/output status=progress
Let us pass the progress option to see periodic transfer statistics using GNU dd command:
# dd if=/dev/sda of=/dev/sdb bs=1024k status=progress
Gif.01: Linux monitor the progress of dd command
No need to use sudo. I used sudo because I was trying to read and clone a USB stick.
How do you monitor the progress of dd?
Here is another example. First, find out your USB device name using the grep command and hwinfo command:
grep -Ff
Output:
Next, unmount the device under Linux:
sudo umount /dev/sdc
Finally, write an iso image to USB device named /dev/sdc and monitor the progress of dd:
sudo dd if=openSUSE-Leap-15.1-DVD-x86_64.iso of=/dev/sdc bs=4M status=progress
Sample outputs:
Use pv command monitor the progress of dd command and see status
Another option is to use pv command which allows you to see the progress of data through a pipeline. You need to install pv command as described here. Once installed, type the following commands to see the status bar. Please note that if standard input is not a file and no size was given with the -s option, the progress bar cannot indicate how close to completion the transfer is, so it will just move left and right to indicate that data is moving. It will also show average MB/s rate:
Copy /dev/sda to to /dev/sdb:
pv -tpreb /dev/sda | dd of=/dev/sdb bs=64M
OR
pv -tpreb /dev/sda | dd of=/dev/sdb bs=4096 conv=notrunc,noerror
Fig.01: pv and dd in action
Fig.02: Show the Status of dd Command in progress using pv and dialog command
Examples: Use gnu dd command from coreutils version 8.24 or above only
Here is another example from my Mac OS X/MacOS:
$ sudo gdd if=ZeroShell-3.6.0-USB.img of=/dev/disk5 bs=1024k status=progress
Fig.03: GNU dd displaying progress
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How do you monitor the progress of dd on Linux?
If you are using an older version of dd or cannot install the pv command, try the following simple one-liner bash shell while loop/command:
Conclusion
The dd command is wonderful, and there are various ways to display a progress indicator with dd. You learned how to monitor the progress of dd using the inbuilt status=progress option to the dd command. Another option is to use the pv tool. Finally, you learned that how to show dd progress in Linux without using pv or status= progress option. See GNU dd man page documentation for more info.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
For Unix users without GNU dd version:
$ tmux
$ dd if=/dev/urandom of=/dev/null bs=16k count=100000
Keep running dd and switch to a new tmux window/pane by hitting ctrl-b-c. Show pid
$ ps aux | grep dd
Type that pid as follows to see progress:
$ kill -SIGUSR1 (pid)
$ tmux attach
We see
OR you could use dcfldd, if your distro/OS has it (Debian does). The awkward acronym stems from it being the Department of Defense Computer Forensics Lab’s version of dd.
or try dcfldd, the Department of Defense Computer Forensics Lab’s dd.
Much better for folks without GNU/dd:
killall -USR1 dd
And to make it beautiful, instead of running dialog, you can run zenity —progress —title «Working. «.
how about?
watch -n 10 ‘killall -USR1 dd’
I use this command to create my Raspberry Pi compressed images
(pv -n /dev/sda | gzip -c | dd of=GentooV2.gz bs=128M conv=notrunc,noerror) 2>&1 | dialog —gauge «Dump running» 10 70 0
It’s better looking than kill -USR1
It may look nicer than kill -USR1 but it’s more complicated to set up. And just hitting up then enter in a second terminal after doing it once is much easier.
*not much easier. Just simple. Typo. The point is you can just check up on it rather than having another process always polling the dd process (dd actually does stop to report the progress).
You wrote:
Copy /dev/sda to to /deb/sdb:
Surely you meant Copy /dev/sda to to /dev/sdb:
That’s dev, not deb. Please correct this, and try to heed your own warning about executing with care.
New version of coreutils (8.24) adding a status progress to dd tool:
Usage on Xubuntu 15.10:
Open terminal shell and type these commands:
sudo ./dd if=/dev/sdc of=/dev/sda conv=noerror status=progress
You will see: Bytes, Seconds and Velocity (Bytes/seconds)
To check versions of dd:
New (cd coreutils-8.24/src):
It be nice to have something that says what the numbers mean wile copying. I am copying a 6TB to a 6TB and it’s been over a day and I guess it only about 4th way because it shows like this:
$ dd if=/dev/sdc1 of=/dev/sdh1 bs=64k conv=noerror,sync status=progress
2211815555072 bytes (2.2 TB, 2.0 TiB) copied, 93833 s, 23.6 MB/s
So I guess the 2.2TB means it copy that much so fair and maybe the 2.0 TiB is how much it has to go? Not sure. Been looking to find this answer and have not found it yet.
2.2TB ‘Tera’bytes = 2.0 TiB, ‘Tebi’bytes.
The difference is bits are by definition binary. Since computers came to be everything was measured in effectively multiples of powers of 2.
Then marketing came in and said ‘well, metric is multiples of powers of 10, and we’ve been using these metric names forever to roughly approximate the order of magnitude for a given power-of-2 binary size. let’s keep using the metric names but instead properly count with 10s and make the drives sound the same size but in effect be physically able to to contain less 1s and 0s than the equivalent binary size’
So the geeks said ‘this is wrong, we’ll make new terms that indicate the binary powers and not the metric terms.
Thus became why we now have both the metric, 10^x sizes of ‘kilo’, ‘mega’, ‘giga’, ‘tera’, etc, along with the new binary 2^x sizes of ‘kibi’, ‘mebi’, ‘tebi’, ‘gibi’, etc ..
The ‘bi’ means a binary size.
1 ‘kilo’ byte is 1000 bytes. 1 ‘kibi’ byte is 1024.
Источник