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

# range action<br />

# 1 s/.* //p<br />

# The line number is in the range, so it executes the action:<br />

# tries to substitute the longest string ending with a space in the line<br />

# ("0000000 ") with nothing (//), and if it succeeds, prints the result<br />

# ("p" is a flag to the "s" command here, this is different from the "p" command).<br />

# sed is now ready to continue reading its input. (Note that before<br />

# continuing, if −n option had not been passed, sed would have printed<br />

# the line once again).<br />

# Now, sed reads the remainder of the characters, and finds the end of the file.<br />

# It is now ready to process its 2nd line (which is also numbered '$' as<br />

# it's the last one).<br />

# It sees it is not matched by any , so its job is done.<br />

# In few word this sed commmand means:<br />

# "On the first line only, remove any character up to the right−most space,<br />

# then print it."<br />

# A better way to do this would have been:<br />

# sed −e 's/.* //;q'<br />

# Here, two s (could have been written<br />

# sed −e 's/.* //' −e q):<br />

# range action<br />

# nothing (matches line) s/.* //<br />

# nothing (matches line) q (quit)<br />

# Here, sed only reads its first line of input.<br />

# It performs both actions, and prints the line (substituted) before quitting<br />

# (because of the "q" action) since the "−n" option is not passed.<br />

# =================================================================== #<br />

# A simpler altenative to the above 1−line script would be:<br />

# head −c4 /dev/urandom| od −An −tu4<br />

exit 0<br />

tail<br />

See also Example 12−30.<br />

lists the end of a file to stdout (the default is 10 lines). Commonly used to keep track of changes to<br />

a system logfile, using the −f option, which outputs lines appended to the file.<br />

Example 12−11. Using tail to monitor the system log<br />

#!/bin/bash<br />

filename=sys.log<br />

cat /dev/null > $filename; echo "Creating / cleaning out file."<br />

# Creates file if it does not already exist,<br />

#+ and truncates it to zero length if it does.<br />

# : > filename and > filename also work.<br />

tail /var/log/messages > $filename<br />

Chapter 12. External Filters, Programs and Commands 165

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

Saved successfully!

Ooh no, something went wrong!