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 />

Another application of /dev/zero is to "zero out" a file of a designated size for a special purpose,<br />

such as mounting a filesystem on a loopback device (see Example 13−6) or securely deleting a file<br />

(see Example 12−42).<br />

Example 29−3. Creating a ramdisk<br />

#!/bin/bash<br />

# ramdisk.sh<br />

# A "ramdisk" is a segment of system RAM memory<br />

#+ that acts as if it were a filesystem.<br />

# Its advantage is very fast access (read/write time).<br />

# Disadvantages: volatility, loss of data on reboot or powerdown.<br />

# less RAM available to system.<br />

#<br />

# What good is a ramdisk?<br />

# Keeping a large dataset, such as a table or dictionary on ramdisk<br />

#+ speeds up data lookup, since memory access is much faster than disk access.<br />

E_NON_ROOT_USER=70<br />

ROOTUSER_NAME=root<br />

MOUNTPT=/mnt/ramdisk<br />

SIZE=2000<br />

BLOCKSIZE=1024<br />

DEVICE=/dev/ram0<br />

# Must run as root.<br />

# 2K blocks (change as appropriate)<br />

# 1K (1024 byte) block size<br />

# First ram device<br />

username=`id −nu`<br />

if [ "$username" != "$ROOTUSER_NAME" ]<br />

then<br />

echo "Must be root to run \"`basename $0`\"."<br />

exit $E_NON_ROOT_USER<br />

fi<br />

if [ ! −d "$MOUNTPT" ]<br />

then<br />

mkdir $MOUNTPT<br />

fi<br />

# Test whether mount point already there,<br />

#+ so no error if this script is run<br />

#+ multiple times.<br />

dd if=/dev/zero of=$DEVICE count=$SIZE bs=$BLOCKSIZE # Zero out RAM device.<br />

mke2fs $DEVICE<br />

# Create an ext2 filesystem on it.<br />

mount $DEVICE $MOUNTPT<br />

# Mount it.<br />

chmod 777 $MOUNTPT<br />

# So ordinary user can access ramdisk.<br />

# However, must be root to unmount it.<br />

echo "\"$MOUNTPT\" now available for use."<br />

# The ramdisk is now accessible for storing files, even by an ordinary user.<br />

# Caution, the ramdisk is volatile, and its contents will disappear<br />

#+ on reboot or power loss.<br />

# Copy anything you want saved to a regular directory.<br />

# After reboot, run this script again to set up ramdisk.<br />

# Remounting /mnt/ramdisk without the other steps will not work.<br />

exit 0<br />

Chapter 29. Of Zeros and Nulls 318

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

Saved successfully!

Ooh no, something went wrong!