27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

#!/bin/bash<br />

# Generates a log file in current directory<br />

# from the tail end of /var/log/messages.<br />

# Note: /var/log/messages must be world readable<br />

# if this script invoked by an ordinary user.<br />

# #root chmod 644 /var/log/messages<br />

LINES=5<br />

( date; uname −a ) >>logfile<br />

# Time and machine name<br />

echo −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− >>logfile<br />

tail −$LINES /var/log/messages | xargs | fmt −s >>logfile<br />

echo >>logfile<br />

echo >>logfile<br />

exit 0<br />

# Exercise:<br />

# −−−−−−−−<br />

# Modify this script to track changes in /var/log/messages at intervals<br />

#+ of 20 minutes.<br />

# Hint: Use the "watch" command.<br />

Example 12−5. copydir, copying files in current directory to another, using xargs<br />

#!/bin/bash<br />

# Copy (verbose) all files in current directory<br />

# to directory specified on command line.<br />

if [ −z "$1" ] # Exit if no argument given.<br />

then<br />

echo "Usage: `basename $0` directory−to−copy−to"<br />

exit 65<br />

fi<br />

ls . | xargs −i −t cp ./{} $1<br />

# This is the exact equivalent of<br />

# cp * $1<br />

# unless any of the filenames has "whitespace" characters.<br />

expr<br />

exit 0<br />

All−purpose expression evaluator: Concatenates and evaluates the arguments according to the<br />

operation given (arguments must be separated by spaces). Operations may be arithmetic, comparison,<br />

string, or logical.<br />

expr 3 + 5<br />

returns 8<br />

expr 5 % 3<br />

returns 2<br />

expr 5 \* 3<br />

returns 15<br />

Chapter 12. External Filters, Programs and Commands 154

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!