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

then<br />

# the corresponding process exists.<br />

echo "Process #$1 invoked by $exe_file."<br />

else<br />

echo "No such process running."<br />

fi<br />

# This elaborate script can *almost* be replaced by<br />

# ps ax | grep $1 | awk '{ print $5 }'<br />

# However, this will not work...<br />

# because the fifth field of 'ps' is argv[0] of the process,<br />

# not the executable file path.<br />

#<br />

# However, either of the following would work.<br />

# find /proc/$1/exe −printf '%l\n'<br />

# lsof −aFn −p $1 −d txt | sed −ne 's/^n//p'<br />

# Additional commentary by Stephane Chazelas.<br />

exit 0<br />

Example 28−2. On−line connect status<br />

#!/bin/bash<br />

PROCNAME=pppd # ppp daemon<br />

PROCFILENAME=status # Where to look.<br />

NOTCONNECTED=65<br />

INTERVAL=2<br />

# Update every 2 seconds.<br />

pidno=$( ps ax | grep −v "ps ax" | grep −v grep | grep $PROCNAME | awk '{ print $1 }' )<br />

# Finding the process number of 'pppd', the 'ppp daemon'.<br />

# Have to filter out the process lines generated by the search itself.<br />

#<br />

# However, as Oleg Philon points out,<br />

#+ this could have been considerably simplified by using "pidof".<br />

# pidno=$( pidof $PROCNAME )<br />

#<br />

# Moral of the story:<br />

#+ When a command sequence gets too complex, look for a shortcut.<br />

if [ −z "$pidno" ] # If no pid, then process is not running.<br />

then<br />

echo "Not connected."<br />

exit $NOTCONNECTED<br />

else<br />

echo "Connected."; echo<br />

fi<br />

while [ true ]<br />

do<br />

# Endless loop, script can be improved here.<br />

if [ ! −e "/proc/$pidno/$PROCFILENAME" ]<br />

# While process running, then "status" file exists.<br />

then<br />

echo "Disconnected."<br />

exit $NOTCONNECTED<br />

fi<br />

Chapter 28. /dev and /proc 314

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

Saved successfully!

Ooh no, something went wrong!