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.

34.7. Assorted Tips<br />

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

• To keep a record of which user scripts have run during a particular sesssion or over a number of<br />

sessions, add the following lines to each script you want to keep track of. This will keep a continuing<br />

file record of the script names and invocation times.<br />

# Append (>>) following to end of each script tracked.<br />

date>> $SAVE_FILE<br />

echo $0>> $SAVE_FILE<br />

echo>> $SAVE_FILE<br />

#Date and time.<br />

#Script name.<br />

#Blank line as separator.<br />

# Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc<br />

# (something like ~/.scripts−run)<br />

•<br />

The >> operator appends lines to a file. What if you wish to prepend a line to an existing file, that is,<br />

to paste it in at the beginning?<br />

file=data.txt<br />

title="***This is the title line of data text file***"<br />

echo $title | cat − $file >$file.new<br />

# "cat −" concatenates stdout to $file.<br />

# End result is<br />

#+ to write a new file with $title appended at *beginning*.<br />

Of course, sed can also do this.<br />

• A shell script may act as an embedded command inside another shell script, a Tcl or wish script, or<br />

even a Makefile. It can be invoked as an external shell command in a C program using the<br />

system() call, i.e., system("script_name");.<br />

• Put together files containing your favorite and most useful definitions and functions. As necessary,<br />

"include" one or more of these "library files" in scripts with either the dot (.) or source command.<br />

# SCRIPT LIBRARY<br />

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

# Note:<br />

# No "#!" here.<br />

# No "live code" either.<br />

# Useful variable definitions<br />

ROOT_UID=0 # Root has $UID 0.<br />

E_NOTROOT=101<br />

# Not root user error.<br />

MAXRETVAL=256<br />

# Maximum (positive) return value of a function.<br />

SUCCESS=0<br />

FAILURE=−1<br />

# Functions<br />

Usage ()<br />

{<br />

if [ −z "$1" ]<br />

then<br />

# "Usage:" message.<br />

# No arg passed.<br />

Chapter 34. Miscellany 347

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

Saved successfully!

Ooh no, something went wrong!