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

# The "strings" command lists strings in binary files.<br />

# Output then piped to "grep", which tests for desired string.<br />

do<br />

echo $word<br />

done<br />

# As S.C. points out, the above for−loop could be replaced with the simpler<br />

# strings "$2" | grep "$1" | tr −s "$IFS" '[\n*]'<br />

# Try something like "./bin−grep.sh mem /bin/ls" to exercise this script.<br />

exit 0<br />

More of the same.<br />

Example 10−8. Listing all users on the system<br />

#!/bin/bash<br />

# userlist.sh<br />

PASSWORD_FILE=/etc/passwd<br />

n=1 # User number<br />

for name in $(awk 'BEGIN{FS=":"}{print $1}' < "$PASSWORD_FILE" )<br />

# Field separator = : ^^^^^^<br />

# Print first field ^^^^^^^^<br />

# Get input from password file ^^^^^^^^^^^^^^^^^<br />

do<br />

echo "USER #$n = $name"<br />

let "n += 1"<br />

done<br />

# USER #1 = root<br />

# USER #2 = bin<br />

# USER #3 = daemon<br />

# ...<br />

# USER #30 = bozo<br />

exit 0<br />

A final example of the [list] resulting from command substitution.<br />

Example 10−9. Checking all the binaries in a directory for authorship<br />

#!/bin/bash<br />

# findstring.sh:<br />

# Find a particular string in binaries in a specified directory.<br />

directory=/usr/bin/<br />

fstring="Free Software Foundation" # See which files come from the FSF.<br />

for file in $( find $directory −type f −name '*' | sort )<br />

do<br />

strings −f $file | grep "$fstring" | sed −e "s%$directory%%"<br />

# In the "sed" expression,<br />

Chapter 10. Loops and Branches 107

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

Saved successfully!

Ooh no, something went wrong!