lolikandr lolikandr - 2 months ago 7
Bash Question

How to correctly set pv size in shell script

I am writing backup script and want to see correct progress of tar.
Main part of script:

backup_file="root-backup-$(date +%Y.%m.%d-%H.%M.%S).tar"
sudo -v
sudo mount /dev/vg/root /mnt
time sudo sh -c "cd /mnt; tar --xattrs -cf - . | pv -s $(du -sb | grep -o '[0-9]*') > /backup/${backup_file}"


But pv show fast filling progress bar and then number increasing up to 100000%.

Upd1. Misprints fixed in script. Actually it works, but progress bar is not correct.

Answer

I found the problem: $(du -sb | grep -o '[0-9]*') is not calling under new subshell - it is calling as command substitution.

So, before run sudo sh -c bash calls $(du -sb | grep -o '[0-9]*') in some current directory (that was smaller in my case) and substitute result into string.

As a result pv -s has incorrect size and show incorrect progress.

I've decided to prevent substitution surrounding sign $ with single quotes:

time sudo sh -c "cd /mnt; tar --xattrs -cf - . | pv -s "'$'"(du -sb | grep -o '[0-9]*') > /backup/${backup_file}"

Comments