27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

To demonstrate just how versatile dd is, let's use it to capture keystrokes.<br />

Example 12−41. Capturing Keystrokes<br />

#!/bin/bash<br />

# Capture keystrokes without needing to press ENTER.<br />

keypresses=4<br />

# Number of keypresses to capture.<br />

old_tty_setting=$(stty −g)<br />

# Save old terminal settings.<br />

echo "Press $keypresses keys."<br />

stty −icanon −echo<br />

keys=$(dd bs=1 count=$keypresses 2> /dev/null)<br />

# 'dd' uses stdin, if "if" not specified.<br />

# Disable canonical mode.<br />

# Disable local echo.<br />

stty "$old_tty_setting"<br />

# Restore old terminal settings.<br />

echo "You pressed the \"$keys\" keys."<br />

# Thanks, S.C. for showing the way.<br />

exit 0<br />

The dd command can do random access on a data stream.<br />

echo −n . | dd bs=1 seek=4 of=file conv=notrunc<br />

# The "conv=notrunc" option means that the output file will not be truncated.<br />

# Thanks, S.C.<br />

The dd command can copy raw data and disk images to and from devices, such as floppies and tape<br />

drives (Example A−6). A common use is creating boot floppies.<br />

dd if=kernel−image of=/dev/fd0H1440<br />

Similarly, dd can copy the entire contents of a floppy, even one formatted with a "foreign" OS, to the<br />

hard drive as an image file.<br />

dd if=/dev/fd0 of=/home/bozo/projects/floppy.img<br />

Other applications of dd include initializing temporary swap files (Example 29−2) and ramdisks<br />

(Example 29−3). It can even do a low−level copy of an entire hard drive partition, although this is not<br />

necessarily recommended.<br />

People (with presumably nothing better to do with their time) are constantly thinking of interesting<br />

applications of dd.<br />

Example 12−42. Securely deleting a file<br />

#!/bin/bash<br />

Chapter 12. External Filters, Programs and Commands 209

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!