| 1 | #!/bin/bash |
| 2 | # Creating a swap file. |
| 3 | |
| 4 | # A swap file provides a temporary storage cache |
| 5 | #+ which helps speed up certain filesystem operations. |
| 6 | |
| 7 | ROOT_UID=0 # Root has $UID 0. |
| 8 | E_WRONG_USER=85 # Not root? |
| 9 | |
| 10 | FILE=/swap |
| 11 | BLOCKSIZE=1024 |
| 12 | MINBLOCKS=40 |
| 13 | SUCCESS=0 |
| 14 | |
| 15 | |
| 16 | # This script must be run as root. |
| 17 | if [ "$UID" -ne "$ROOT_UID" ] |
| 18 | then |
| 19 | echo; echo "You must be root to run this script."; echo |
| 20 | exit $E_WRONG_USER |
| 21 | fi |
| 22 | |
| 23 | |
| 24 | blocks=${1:-$MINBLOCKS} # Set to default of 40 blocks, |
| 25 | #+ if nothing specified on command-line. |
| 26 | # This is the equivalent of the command block below. |
| 27 | # -------------------------------------------------- |
| 28 | # if [ -n "$1" ] |
| 29 | # then |
| 30 | # blocks=$1 |
| 31 | # else |
| 32 | # blocks=$MINBLOCKS |
| 33 | # fi |
| 34 | # -------------------------------------------------- |
| 35 | |
| 36 | |
| 37 | if [ "$blocks" -lt $MINBLOCKS ] |
| 38 | then |
| 39 | blocks=$MINBLOCKS # Must be at least 40 blocks long. |
| 40 | fi |
| 41 | |
| 42 | |
| 43 | ###################################################################### |
| 44 | echo "Creating swap file of size $blocks blocks (KB)." |
| 45 | dd if=/dev/zero of=$FILE bs=$BLOCKSIZE count=$blocks # Zero out file. |
| 46 | mkswap $FILE $blocks # Designate it a swap file. |
| 47 | swapon $FILE # Activate swap file. |
| 48 | retcode=$? # Everything worked? |
| 49 | # Note that if one or more of these commands fails, |
| 50 | #+ then it could cause nasty problems. |
| 51 | ###################################################################### |
| 52 | |
| 53 | # Exercise: |
| 54 | # Rewrite the above block of code so that if it does not execute |
| 55 | #+ successfully, then: |
| 56 | # 1) an error message is echoed to stderr, |
| 57 | # 2) all temporary files are cleaned up, and |
| 58 | # 3) the script exits in an orderly fashion with an |
| 59 | #+ appropriate error code. |
| 60 | |
| 61 | echo "Swap file created and activated." |
| 62 | |
| 63 | exit $retcode |