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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

test.tar.gz: gzip compressed data, deflated, last modified: Sun Sep 16 13:34:51 2001, os:<br />

bash file −z test.tar.gz<br />

test.tar.gz: GNU tar archive (gzip compressed data, deflated, last modified: Sun Sep 16 13<br />

Example 12−24. stripping comments from C program files<br />

#!/bin/bash<br />

# strip−comment.sh: Strips out the comments (/* COMMENT */) in a C program.<br />

E_NOARGS=65<br />

E_ARGERROR=66<br />

E_WRONG_FILE_TYPE=67<br />

if [ $# −eq "$E_NOARGS" ]<br />

then<br />

echo "Usage: `basename $0` C−program−file" >&2 # Error message to stderr.<br />

exit $E_ARGERROR<br />

fi<br />

# Test for correct file type.<br />

type=`eval file $1 | awk '{ print $2, $3, $4, $5 }'`<br />

# "file $1" echoes file type...<br />

# then awk removes the first field of this, the filename...<br />

# then the result is fed into the variable "type".<br />

correct_type="ASCII C program text"<br />

if [ "$type" != "$correct_type" ]<br />

then<br />

echo<br />

echo "This script works on C program files only."<br />

echo<br />

exit $E_WRONG_FILE_TYPE<br />

fi<br />

# Rather cryptic sed script:<br />

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

sed '<br />

/^\/\*/d<br />

/.*\/\*/d<br />

' $1<br />

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

# Easy to understand if you take several hours to learn sed fundamentals.<br />

# Need to add one more line to the sed script to deal with<br />

#+ case where line of code has a comment following it on same line.<br />

# This is left as a non−trivial exercise.<br />

# Also, the above code deletes lines with a "*/" or "/*",<br />

# not a desirable result.<br />

exit 0<br />

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

# Code below this line will not execute because of 'exit 0' above.<br />

Chapter 12. External Filters, Programs and Commands 180

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

Saved successfully!

Ooh no, something went wrong!