Unix Shell Scripts   «Prev 

Entering shell script commands at the command line

  1. Enter the following command to start a Bourne shell: sh
  2. Enter the following command at the command line: if [ -f /etc/database.conf.sample ]
  3. Enter the following command: then
  4. Enter the following command: cp /etc/database.conf.sample /etc/database.conf
  5. Enter the following command: else
  6. Enter the following command: echo No sample configuration file is available.
  7. Enter the following command: fi
  8. The command is executed and displays the results of the commands you entered.

Example 4-1: Cleanup: A script to clean up log files in /var/log
# Cleanup
# Run as root, of course.
cd /var/log
cat /dev/null > messages
cat /dev/null > wtmp
echo "Log files cleaned up."

A set of commands that could just as easily have been invoked one by one from the command-line on the console or in a terminal window.
The advantages of placing the commands in a script go far beyond not having to retype them time and again.
The script becomes a program or tool and it can easily be modified or customized for a particular application.
Example 4-2: cleanup: An improved clean-up script
# Proper header for a Bash script.
# Cleanup, version 2
# Run as root, of course.
# Insert code here to print error message and exit if not root.
# Variables are better than hard-coded values.
cat /dev/null > messages
cat /dev/null > wtmp
echo "Logs cleaned up."
exit # The right and proper method of "exiting" from a script.
# A bare "exit" (no parameter) returns the exit status
#+ of the preceding command.