SPR720 BASH Scripting Lab

From CDOT Wiki
Jump to: navigation, search

Running a Bash Script

Enter this script into the file "script1" in the current directory (it's a good idea to create a directory for this lab):

#!/bin/bash
SECRET=$(( RANDOM % 100 + 1))
INPUT=0
GUESSES=0

echo "Guess the secret: a number between 1 and 100."
while [ "$INPUT" -ne "$SECRET" ]
do

       echo -n "Your guess: "
       read INPUT

       if [ "$INPUT" -eq "$SECRET" ]
       then
               echo "Correct!"
       elif [ "$INPUT" -gt "$SECRET" ]
       then
               echo "Too high."
       else
               echo "Too low."
       fi

       ((GUESSES++))

done

echo "You took $GUESSES tries."

Make the script executable:

chmod u+x script1

Try running the script:

script1

If that doesn't work, specify the directory:

./script1

Or add the current directory to the path:

PATH="$PATH:."

Read through the script and make sure you understand what it does. Use BASH wiki page and the bash manpage for reference.

Reading Bash Scripts

Guess what each of these scripts does, and then test your assumption.

#!/bin/bash
 
if false
then
        echo "1"
elif true
then
        echo "2"
else
        echo "3"
fi
#!/bin/bash
for ((x=0; x<5; x++))
do
   echo $x
done
#!/bin/bash
for NAME in /etc/*
do
  if [ -r "$NAME" -a -f "$NAME" ]
  then
     wc -c "$NAME"
  fi
done

Writing BASH Scripts

Write scripts to do three of the following tasks:

  1. Loop through the files in your home directory, and for each readable file, ask whether the file should be printed, mailed to you, or ignored (P/M/I) and then take the appropriate action.
  2. Display the longest and shortest usernames on the system (usernames are in the first field in /etc/passwd).
  3. Count the number of users with user IDs between 500 and 10000 on the system (user IDs are the third field in /etc/passwd).
  4. Display the names of any filesystems which have less than 10% free space available (see the df command for this information).
  5. Ask the user for an e-mail address, then send the output of the dmesg command to that address.
  6. Count the number of files in the user's home directory which are not readable.
  7. For each directory in the $PATH, display the number of executable files in that directory.

Hints and suggestions

See the manpages for these commands:

  • wc (see the -w, -c, -l, and -L options)
  • lpr
  • mail
  • cut (see the -d and -f options)
  • df

Post your answer in discussion...

Deliverable

Blog about your experience with this lab, and include a link to one of the scripts you've written.