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

# All cookies now get sent to a black hole, rather than saved to disk.<br />

Uses of /dev/zero<br />

Like /dev/null, /dev/zero is a pseudo file, but it actually contains nulls (numerical zeros, not<br />

the ASCII kind). Output written to it disappears, and it is fairly difficult to actually read the nulls in<br />

/dev/zero, though it can be done with od or a hex editor. The chief use for /dev/zero is in<br />

creating an initialized dummy file of specified length intended as a temporary swap file.<br />

Example 29−2. Setting up a swapfile using /dev/zero<br />

#!/bin/bash<br />

# Creating a swapfile.<br />

# This script must be run as root.<br />

ROOT_UID=0 # Root has $UID 0.<br />

E_WRONG_USER=65 # Not root?<br />

FILE=/swap<br />

BLOCKSIZE=1024<br />

MINBLOCKS=40<br />

SUCCESS=0<br />

if [ "$UID" −ne "$ROOT_UID" ]<br />

then<br />

echo; echo "You must be root to run this script."; echo<br />

exit $E_WRONG_USER<br />

fi<br />

blocks=${1:−$MINBLOCKS}<br />

# Set to default of 40 blocks,<br />

#+ if nothing specified on command line.<br />

# This is the equivalent of the command block below.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# if [ −n "$1" ]<br />

# then<br />

# blocks=$1<br />

# else<br />

# blocks=$MINBLOCKS<br />

# fi<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

if [ "$blocks" −lt $MINBLOCKS ]<br />

then<br />

blocks=$MINBLOCKS<br />

fi<br />

# Must be at least 40 blocks long.<br />

echo "Creating swap file of size $blocks blocks (KB)."<br />

dd if=/dev/zero of=$FILE bs=$BLOCKSIZE count=$blocks # Zero out file.<br />

mkswap $FILE $blocks<br />

swapon $FILE<br />

# Designate it a swap file.<br />

# Activate swap file.<br />

echo "Swap file created and activated."<br />

exit $SUCCESS<br />

Chapter 29. Of Zeros and Nulls 317

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

Saved successfully!

Ooh no, something went wrong!