LDP/LDP/guide/docbook/abs-guide/ex73.sh

64 lines
1.7 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2008-05-09 18:58:34 +00:00
# Creating a swap file.
# A swap file provides a temporary storage cache
#+ which helps speed up certain filesystem operations.
2001-07-10 14:25:50 +00:00
2001-09-04 13:27:31 +00:00
ROOT_UID=0 # Root has $UID 0.
2008-11-23 22:43:47 +00:00
E_WRONG_USER=85 # Not root?
2001-09-04 13:27:31 +00:00
2001-07-10 14:25:50 +00:00
FILE=/swap
BLOCKSIZE=1024
2001-09-04 13:27:31 +00:00
MINBLOCKS=40
2001-07-10 14:25:50 +00:00
SUCCESS=0
2004-07-12 13:08:16 +00:00
# This script must be run as root.
2001-09-04 13:27:31 +00:00
if [ "$UID" -ne "$ROOT_UID" ]
then
echo; echo "You must be root to run this script."; echo
exit $E_WRONG_USER
fi
2001-07-10 14:25:50 +00:00
2002-07-22 15:11:51 +00:00
blocks=${1:-$MINBLOCKS} # Set to default of 40 blocks,
2008-11-23 22:43:47 +00:00
#+ if nothing specified on command-line.
2002-07-22 15:11:51 +00:00
# This is the equivalent of the command block below.
# --------------------------------------------------
# if [ -n "$1" ]
# then
# blocks=$1
# else
# blocks=$MINBLOCKS
# fi
# --------------------------------------------------
2001-09-04 13:27:31 +00:00
if [ "$blocks" -lt $MINBLOCKS ]
then
blocks=$MINBLOCKS # Must be at least 40 blocks long.
fi
2001-07-10 14:25:50 +00:00
2006-10-11 16:39:10 +00:00
######################################################################
2001-09-04 13:27:31 +00:00
echo "Creating swap file of size $blocks blocks (KB)."
dd if=/dev/zero of=$FILE bs=$BLOCKSIZE count=$blocks # Zero out file.
mkswap $FILE $blocks # Designate it a swap file.
swapon $FILE # Activate swap file.
2008-07-20 23:16:47 +00:00
retcode=$? # Everything worked?
2006-10-11 16:39:10 +00:00
# Note that if one or more of these commands fails,
#+ then it could cause nasty problems.
######################################################################
# Exercise:
# Rewrite the above block of code so that if it does not execute
#+ successfully, then:
# 1) an error message is echoed to stderr,
# 2) all temporary files are cleaned up, and
# 3) the script exits in an orderly fashion with an
#+ appropriate error code.
2001-07-10 14:25:50 +00:00
2001-09-04 13:27:31 +00:00
echo "Swap file created and activated."
2001-07-10 14:25:50 +00:00
2008-07-20 23:16:47 +00:00
exit $retcode