BAShing sudo through a Pipe

I fixed my dad’s Windows box and after getting it all set up I figured I would create a backup image based on the completed build, installations, and updates.  A nice best-of restore point, eh?

So I booted the machine into an Ubuntu 10.04 Live CD, created the necessary partition using gparted, and mounted the partition onto which I would create the backup.

I tried using dd to create the backup image, but found that my backup space was too small for the full OS partition.  To build the backup I ran this:

#
#
# dd command from partition to file

sudo dd if=/dev/hdb of=/path/to/image

#

Not such a problem because I could of course pipe my dd output into gzip and compress my backup image.  Typically if you want to compress the  image you would merely pipe the dd output into gzip like thus:

#
#
# normal format for piping dd into gzip

dd if=/dev/hdb | gzip > /path/to/image.gz

#

The problem is that if I used sudo on this full command I hit a permission denied error.  This is because sudo only applies to the first command (dd) and not to any subsequent commands (in this case gzip)—sudo does not flow through the pipe.  However, I pulled out my trusty BASH Cookbook and found a way to run the whole thing under sudo:

#
#
# proper way to manage using dd, gzip, and sudo

sudo bash -c 'dd if=/dev/hdb | gzip > /path/to/image.gz'

#

This runs a bash terminal as root (non-interactive) for the duration of the quoted command and then exits back into the interactive terminal I had been using.  Worked great.

(The drive I backed up was > adjust your code accordingly.)

Thanks, O’Reilly.

Share

5 thoughts on “BAShing sudo through a Pipe

Leave a Reply to JamesIsIn Cancel reply

Your email address will not be published. Required fields are marked *