Wednesday, 5 September 2012

Shell Script Examples ?

The sha-bang ( #!at the head of a script tells your system that this file is a set of commands to be fed to the command interpreter indicated.

#!/bin/sed -f
#!/bin/awk -f

Note again that #!/bin/sh invokes the default shell interpreter,

Example 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."

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. 


3. Backup of all files changed in last day


#  Backs up all files in current directory modified within last 24 hours
#+ in a "tarball" (tarred and gzipped file).

BACKUPFILE=backup-$(date +%m-%d-%Y)
#                 Embeds date in backup filename.
#                 Thanks, Joshua Tschida, for the idea.

#  If no backup-archive filename specified on command-line,
#+ it will default to "backup-MM-DD-YYYY.tar.gz."

tar cvf - `find . -mtime -1 -type f -print` > $archive.tar
gzip $archive.tar
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."

#  Stephane Chazelas points out that the above code will fail
#+ if there are too many files found
#+ or if any filenames contain blank characters.

# He suggests the following alternatives:
# -------------------------------------------------------------------
#   find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
#      using the GNU version of "find".

#   find . -mtime -1 -type f -exec tar rvf "$archive.tar" '{}' \;
#         portable to other UNIX flavors, but much slower.
# -------------------------------------------------------------------

exit 0


4. exit / exit status


echo hello
echo $?    #Exitstatus 0 command executed successfully

lskdf      # Unrecognized command.
echo $?    # Non-zero exit status command failed to execute.


exit 113   # Will return 113 to shell.
           # To verify this, type "echo $?" after script terminates.

#  By convention, an 'exit 0' indicates success,
#+ while a non-zero exit value means an error or anomalous condition.

5. Am I root?

#   Am I root or not?

ROOT_UID=0   # Root has $UID 0.

if [ "$UID" -eq "$ROOT_UID" ]  # Will the real "root" please stand up?
  echo "You are root."
  echo "You are just an ordinary user (but mom loves you just the same)."

exit 0

# ============================================================= #
# Code below will not execute, because the script already exited.

# An alternate method of getting to the root of matters:


username=`id -nu`              # Or...   username=`whoami`
if [ "$username" = "$ROOTUSER_NAME" ]
  echo "Rooty, toot, toot. You are root."
  echo "You are just a regular fella."

6. Using tail to monitor the system log



cat /dev/null > $filename; echo "Creating / cleaning out file."
#  Creates the file if it does not already exist,
#+ and truncates it to zero length if it does.
#  : > filename   and   > filename also work.

tail /var/log/messages > $filename  
# /var/log/messages must have world read permission for this to work.

echo "$filename contains tail end of system log."

exit 0
7. Setting a new password

# For demonstration purposes only.
#                      Not a good idea to actually run this script.
#  This script must be run as root.

ROOT_UID=0         # Root has $UID 0.
E_WRONG_USER=65    # Not root?


if [ "$UID" -ne "$ROOT_UID" ]
  echo; echo "Only root can run this script."; echo
  exit $E_WRONG_USER
  echo "You should know better than to run this script, root."
  echo "Even root users get the blues... "


# Check if bozo lives here.
grep -q "$username" /etc/passwd
if [ $? -ne $SUCCESS ]
  echo "User $username does not exist."
  echo "No password changed."

echo "$NEWPASSWORD" | passwd --stdin "$username"
#  The '--stdin' option to 'passwd' permits
#+ getting a new password from stdin (or a pipe).

echo; echo "User $username's password changed!"

# Using the 'passwd' command in a script is dangerous.

exit 0

No comments:

Post a Comment