<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>awk &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/awk/</link>
	<description>Feed of posts on WordPress.com tagged "awk"</description>
	<pubDate>Tue, 07 Oct 2008 12:30:09 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Google Code Jam - Always Turn Left (Practice Problems)]]></title>
<link>http://tecnologiaecomunicacao.wordpress.com/?p=250</link>
<pubDate>Sat, 04 Oct 2008 11:33:47 +0000</pubDate>
<dc:creator>Phil</dc:creator>
<guid>http://tecnologiaecomunicacao.pt-br.wordpress.com/2008/10/04/google-code-jam-always-turn-left-practice-problems/</guid>
<description><![CDATA[Neste novo desáfio, o objetivo era descrever um labirínto, de acordo como ele estava atravessado, ]]></description>
<content:encoded><![CDATA[<p>Neste <a href="http://code.google.com/codejam/contest/" target="_blank">novo desáfio</a>, o objetivo era descrever um labirínto, de acordo como ele estava atravessado, da entrada para a saída, e de volta. Para atravessar o labirínto, o método usado é o seguinte: cada vez que se encontra uma alternativa de caminho, escolha-se o caminho de esquerda; se chegar a um impasse, vira-se duas vezes pela direita (retorna-se). A versão em inglês do problema segue:</p>
<blockquote>
<p class="problem-item">Problem</p>
<p>You find yourself standing outside of a perfect maze. A maze is defined as "perfect" if it meets the following conditions:</p>
<ol>
<li>It is a rectangular grid of rooms, <strong>R</strong> rows by <strong>C</strong> columns.</li>
<li>There are exactly two openings on the outside of the maze: the entrance and the exit. The entrance is always on the north wall, while the exit could be on any wall.</li>
<li>There is exactly one path between any two rooms in the maze (that is, exactly one path that does not involve backtracking).</li>
</ol>
<p>You decide to solve the perfect maze using the "always turn left" algorithm, which states that you take the leftmost fork at every opportunity. If you hit a dead end, you turn right twice (180 degrees clockwise) and continue. (If you were to stick out your left arm and touch the wall while following this algorithm, you'd solve the maze without ever breaking contact with the wall.) Once you finish the maze, you decide to go the extra step and solve it again (still always turning left), but starting at the exit and finishing at the entrance.</p>
<p>The path you take through the maze can be described with three characters: 'W' means to walk forward into the next room, 'L' means to turn left (or counterclockwise) 90 degrees, and 'R' means to turn right (or clockwise) 90 degrees. You begin outside the maze, immediately adjacent to the entrance, facing the maze. You finish when you have stepped outside the maze through the exit. For example, if the entrance is on the north and the exit is on the west, your path through the following maze would be<code>WRWWLWWLWWLWLWRRWRWWWRWWRWLW</code>:</p>
<p><img src="http://code.google.com/codejam/contest/static/maze.gif" alt="" />If the entrance and exit were reversed such that you began outside the west wall and finished out the north wall, your path would be <code>WWRRWLWLWWLWWLWWRWWRWWLW</code>. Given your two paths through the maze (entrance to exit and exit to entrance), your code should return a description of the maze.</p></blockquote>
<p>Como sempre, o Google Code Jam especifica o formato do arquivo de saída desejado para o programa. Deixo você visitarem a página do site para ver os detalhes. Segue meu programa, novamente em shell+awk (eu consigo desenvolver bem rapidamente usando awk, em particular quando usam-se <em>arrays </em>e carateres)</p>
<blockquote><p><code><br />
#!/bin/bash</code></p>
<p><code>dbg=0<br />
if [ ! -z "$*" ]; then dbg=1 ; fi</code></p>
<p><code> </code><code>awk -v dbg=$dbg 'FNR==1 { cases=$1; cn=0; next }<br />
{<br />
delete x<br />
cn++<br />
if (cn&#62;cases) next<br />
print "Case #"cn":"<br />
r=0<br />
c=1<br />
inout=$1<br />
outin=$2<br />
li=length(inout)<br />
lo=length(outin)<br />
dv=1<br />
dh=0<br />
dir=1<br />
dd[1]=2<br />
dd[2]=4<br />
dd[3]=1<br />
dd[4]=8<br />
mw=1<br />
me=1<br />
ms=0<br />
if (dbg) print "init: dv=1 dh=1 dir=1 r=0 c=1"<br />
for (i=1;i&#60;=li;i++) {<br />
a=substr(inout,i,1)<br />
if (a=="W") {<br />
x[r,c,dir]=1<br />
if (dbg) print "("r","c","dir")=1"<br />
r=r+dv<br />
c=c+dh<br />
dirop=((dir+2)%4)+(dir==2)*4<br />
x[r,c,dirop]=1<br />
if (dbg) print "("r","c","dirop")=1"<br />
} else if (a=="L") {<br />
dir=dir-1+4*(dir==1)<br />
} else if (a=="R") {<br />
dir=(dir%4)+1<br />
}<br />
dv=(dir==1)-(dir==3)<br />
dh=(dir==4)-(dir==2)<br />
if (i</code></p>
<p><code> </code><code>if (r&#62;ms) ms=r<br />
if (c 			if (c&#62;me) me=c<br />
}<br />
if (dbg) print "("a") dv="dv" dh="dh" dir="dir" r="r" c="c<br />
}<br />
# going back: return<br />
dir=((dir%4)+1)%4+1<br />
dv=(dir==1)-(dir==3)<br />
dh=(dir==4)-(dir==2)<br />
if (dbg) print "back: dv="dv" dh="dh" dir="dir" r="r" c="c<br />
for (i=1;i&#60;=lo;i++) {<br />
a=substr(outin,i,1)<br />
if (a=="W") {<br />
x[r,c,dir]=1<br />
if (dbg) print "("r","c","dir")=1"<br />
r=r+dv<br />
c=c+dh<br />
dirop=((dir+2)%4)+(dir==2)*4<br />
x[r,c,dirop]=1<br />
if (dbg) print "("r","c","dirop")=1"<br />
} else if (a=="L") {<br />
dir=dir-1+4*(dir==1)<br />
} else if (a=="R") {<br />
dir=(dir%4)+1<br />
}<br />
dv=(dir==1)-(dir==3)<br />
dh=(dir==4)-(dir==2)<br />
if (i<br />
if (r&#62;ms) ms=r<br />
if (c 			if (c&#62;me) me=c<br />
}<br />
if (dbg) print "("a") dv="dv" dh="dh" dir="dir" r="r" c="c<br />
}<br />
for (r=1; r&#60;=ms; r++) {<br />
for (c=mw;c&#60;=me;c++) {<br />
v=dd[1]*x[r,c,1]+dd[2]*x[r,c,2]+dd[3]*x[r,c,3]+dd[4]*x[r,c,4]<br />
printf substr("0123456789abcdef",1+v,1);<br />
}<br />
print ""<br />
}<br />
if (dbg) {<br />
for (r=0; r&#60;=ms; r++) {<br />
for (c=mw;c&#60;=me;c++) {<br />
if (r&#62;0 &#38;&#38; x[r,c,2]==0) printf "&#124;" &#62;"/dev/stderr"<br />
else printf " " &#62;"/dev/stderr"<br />
if (x[r,c,1]==0) printf "_" &#62;"/dev/stderr"<br />
else printf " " &#62;"/dev/stderr"<br />
if (r&#62;0 &#38;&#38; c==me &#38;&#38; x[r,c,4]==0) printf "&#124;" &#62;"/dev/stderr"<br />
}<br />
print "" &#62;"/dev/stderr"<br />
}<br />
}<br />
}' src.in &#62; src.out<br />
</code></p></blockquote>
<p>Eu inclui uma opção de "debug" no programa (basta passar qualquer argumento ao programa) que apresenta passo-a-passo a travessia do labirínto, e também representa "graficamente" (em modo de texto) o labirínto. Cuidado que testando o programa com os labiríntos de verdade propostos no concurso, muitos estão de grande largura e a representação dos mesmos fica meio "quebrada"...</p>
<p>Abraços,<br />
Phil.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Sage to Google Reader OPML converter]]></title>
<link>http://lookherefirst.wordpress.com/?p=68</link>
<pubDate>Wed, 24 Sep 2008 11:08:34 +0000</pubDate>
<dc:creator>beppe</dc:creator>
<guid>http://lookherefirst.pt-br.wordpress.com/2008/09/24/sage-to-google-reader-opml-converter/</guid>
<description><![CDATA[For some reason, when exporting rss feeds from Sage, a Firefox plugin, to an OPML file it does not s]]></description>
<content:encoded><![CDATA[<p>For some reason, when exporting rss feeds from Sage, a Firefox plugin, to an OPML file it does not save the feed (i.e. the xml/rss/atom/whatever) link, but the feeds themselves, i.e. the content of the feeds.</p>
<p>If you have the same problem, here's a fast-and-dirty solution.</p>
<ol>
<li>export your Firefox bookmarks in HTML format, in a file called, say, bookmarks.html</li>
<li>using a bash shell, extract the feed lines into a file called feeds.xml doing
<pre><strong> grep FEEDURL bookmarks.html &#62; feeds.xml</strong></pre>
</li>
<li>create the following script called "scriptfeed.sh"
<pre><strong>#!/bin/bash
echo "&#60;?xml version=\"1.0\" encoding=\"UTF-8\"?&#62;"
echo "&#60;opml version=\"1.0\"&#62;"
echo "&#60;head&#62;&#60;title&#62;RSS Subscriptions&#60;/title&#62;&#60;/head&#62;"
echo "&#60;body&#62;"
while read line
do
        temp=`echo $line &#124; awk -F"&#60;" {'print $3;'}`
        feed=`echo $temp &#124; awk -F"\"" {'print $2;'}`
        url=`echo $temp &#124; awk -F"\"" {'print $4;'}`
        text=`echo $temp &#124; awk -F"&#62;" {'print $2;'}`
        echo "&#60;outline text=\"$text\""
        echo "  title=\"$text\""
        echo "  type=\"rss\""
        echo "  xmlUrl=\"$feed\""
        echo "  htmlUrl=\"$url\"/&#62;"
done &#60; feeds.xml
echo "&#60;/body&#62;"
echo "&#60;/opml&#62;"</strong></pre>
</li>
<li>Give the script the right to execute
<pre><strong>chmod +x scriptfeed.sh</strong></pre>
</li>
<li>Launch the script on the output file, say, exp.xml
<pre><strong>./scriptfeed.sh &#62; exp.xml</strong></pre>
</li>
</ol>
<p>I know, it's dirty and tricky, but it works :-P</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[AD-04-APPLICATION DESIGNER ]]></title>
<link>http://careeratkbs.wordpress.com/?p=35</link>
<pubDate>Mon, 22 Sep 2008 04:37:01 +0000</pubDate>
<dc:creator>careeratkbs</dc:creator>
<guid>http://careeratkbs.pt-br.wordpress.com/2008/09/22/ad-04-application-designer/</guid>
<description><![CDATA[ AD-04-APPLICATION DESIGNER

Hi,
Here the placement for Application  Designer.
Req.  ID:
Req-AD-04 -]]></description>
<content:encoded><![CDATA[<p><strong><span style="color:#cc0000;"> AD-04-APPLICATION DESIGNER</span></strong></p>
<p align="center"><span style="font-size:x-small;font-family:Arial,Helvetica,sans-serif;"><a href="http://www.jobsearchworld.com/"><img src="http://www.jobsearchworld.com/jobs2.jpg" border="0" alt="jobs" width="253" height="89" /></a></span></p>
<p>Hi,</p>
<p>Here the placement for <strong><span style="color:#660000;">Application  Designer.<br />
</span><span style="color:#ff6600;">Req.  ID:</span><br />
</strong><span style="color:#333399;">Req-AD-04 - Application  Designer<br />
</span><strong><span style="color:#008080;">Primary  Skills:<br />
</span></strong>LDAP,Database systems,Daytona data  management,SQL,UNIX and C development and web development,HTML, JavaScript,  Perl, UNIX, Linux…<br />
<strong><span style="color:#33cccc;">Secondary  Skills:<br />
</span></strong>LDAP, Windows, SQL, AWK, C, CGI..</p>
<p><strong><span style="color:#993366;">Description:<br />
</span></strong>Dynamic  Development Role with Telecom Leader! Project Name Application Designer, Fraud  Management Project Description: Global Fraud Management system which is a  continuous analytical engine and case manager that uses pattern recognition to  detect fraud.</p>
<p><strong><span style="color:#ff00ff;">Job Description: </span></strong></p>
<p>Developer will create new applications and enhance existing application using  C, CGI, JavaScript, Perl, Shell, AWK, HTML, and SQL. Only submit extremely  technically qualified candidates. Also desired:LDAPDatabase systems Daytona data  managementBasic knowledge of database systemsDesign.</p>
<p><strong><span style="color:#800080;">SQL Database  concept:</span></strong></p>
<p>Must be expert in all aspects of UNIX and C development and web  development.Responsible for development and maintenance of mission-critical  applications that support high-visibility client organizations and external  customers on a24×7x365 basis. Technical assessment will be done on candidates.  Background check will be required before the candidate can start the  assignment.</p>
<p><strong><span style="color:#cc99ff;">REQUIRED SKILLS:</span></strong></p>
<p>HTML, JavaScript, Perl, UNIX, Linux</p>
<p><strong><span style="color:#00ffff;">PREFERRED SKILLS:</span></strong></p>
<p>LDAP, Windows, SQL, AWK, C, CGI</p>
<p><span style="color:#00ccff;"><strong>Rate</strong>:</span>DOE,</p>
<p><strong><span style="color:#99cc00;">Job Type</span></strong>: Contract,</p>
<p><strong><span style="color:#008080;">Total Exp</span></strong>: 6+Yrs,</p>
<p><strong><span style="color:#ff99cc;">Duration</span>:</strong> 6+ Months,</p>
<p><strong><span style="color:#993300;">Number Of Openings</span>:</strong> 1,</p>
<p><strong><span style="color:#ff6600;">Location:</span></strong> Florham Park,  NJ</p>
<p><strong><span style="color:#ff99cc;">Contact Us:</span></strong></p>
<p><strong><span style="color:#3333ff;">KBS</span> <span style="color:#ff0000;">consultants</span></strong></p>
<p>Flat H,Kulothungan Apts,</p>
<p>No, 5 Natesan Road,</p>
<p>Ashoknagar,</p>
<p>Chennai 600 083</p>
<p>India</p>
<p>Phone: +91-44 2489 5341 / 2371 9622</p>
<p><strong><span style="color:#993366;">Visit us:</span></strong></p>
<p><strong>Email:</strong>www.kbsconsultants.com</p>
<p><a href="http://www.kbsconsultants.org.in/">www.kbsconsultants.org.in/</a></p>
<p><a href="http://www.kbsconsultants.net.in/">www.kbsconsultants.net.in/</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Bring Me My Pipe]]></title>
<link>http://sansforensics.wordpress.com/?p=132</link>
<pubDate>Wed, 17 Sep 2008 14:47:15 +0000</pubDate>
<dc:creator>jeffbryner</dc:creator>
<guid>http://sansforensics.pt-br.wordpress.com/2008/09/17/bring-me-my-pipe/</guid>
<description><![CDATA[Pipes photo courtesy of tanakawho at flickr.com 
Often used and under appreciated, the pipe feature ]]></description>
<content:encoded><![CDATA[[caption id="attachment_298" align="alignleft" width="180" caption="Pipes photo courtesy of tanakawho at flickr.com "]<a href="http://flickr.com/photos/28481088@N00/"><img class="size-full wp-image-298" title="Pipes" src="http://sansforensics.wordpress.com/files/2008/09/pipes1.jpg" alt="//flickr.com/photos/28481088@N00/" width="180" height="240" /></a>[/caption]
<p>Often used and under appreciated, the <a href="http://en.wikipedia.org/wiki/Pipe_%28Unix%29">pipe</a> feature in unix/linux/dos has to be my favorite tool in incident response and forensics.</p>
<p>Need the device at /dev/sda imaged with progress indicators and an md5sum?</p>
<div style="margin-left:40px;"><code>dd if=/dev/sda&#124; pipebench &#124; tee sda.dd &#124; md5sum &#62;sda.md5.txt<br />
</code></div>
<p>Need a summary of the unique hosts from Internet Explorer's index.dat history file?</p>
<div style="margin-left:40px;"><code>pasco index.dat &#124; grep -v 'javascript\:' &#124; egrep -i 'ftp&#124;http' &#124; sort -k 4 &#124; awk '{print $3}' &#124; awk 'BEGIN {FS="/"}{print $2$3}'&#124; sort &#124; uniq &#124; less</code></div>
<p>No other feature I can think of makes it easier to quickly analyze data. There's even a wiki entry dedicated to pipe 101 <a href="http://en.wikibooks.org/w/index.php?title=Ad_Hoc_Data_Analysis_From_The_Unix_Command_Line">exploration</a>.</p>
<p>Here's my top 3 bash shell pipelines I use every day on my <a href="http://www.gentoo.org/">gentoo</a> linux workstation:</p>
<div style="margin-left:40px;">1) Tailing log files in real-time:</div>
<div style="margin-left:80px;"><code>tail -f tabDelimitedNastyBusyLogfile.txt &#124; remark filterfilehere.txt &#124; awk 'BEGIN {FS="\t"} { print $fieldnumberhere,$fieldnumberhere } system("")'</code></div>
<div style="margin-left:80px;"><code>tail -f tabDelimitedNastyBusyLogfile.txt &#124; egrep -vif whitelistfilehere.txt &#124; awk 'BEGIN {FS="\t"} { print $fieldnumberhere, $fieldnumberhere } system("")'</code></div>
<div style="margin-left:80px;">
<p>Have a busy syslog file (ASA firewall?) to monitor that you couldn't possibly read fast enough? Piping a file through remark or a grep white list can limit what you see while awk can pick out fields in the output to highlight. Remark can easily color code output which is handy for assigning colors to something like IP netblocks, keywords, etc.</p>
<p>Quick frustration avoidance tip: the system("") at the end of the awk script bypasses the internal awk output buffer so you see output right away instead of waiting for your system to flush the buffer.</p>
<p>Do you use the 172.21.0.0/16 private IP space? You can quickly get a visual of good IP ranges with a remark entry like:</p>
<p><code>/172\.21\.([0-9]{1,3}\.)[0-9]{1,3}/g {green }</code></p>
<p>which will color all your private IP space green, making it easy to pick out whether you are the source or destination at a glance.</p>
<p>Alternatively you can filter out/white list entries with a remark entry like</p>
<p><code>/Accessed URL/ skip </code></p>
<p>if you're not interested in those entries, allowing you to hone in on what you're after.</p></div>
<div style="margin-left:40px;">2) while read i</div>
<div style="margin-left:40px;">
<div style="margin-left:40px;">This shell construct:</div>
<div style="margin-left:40px;"><code>somecommand &#124; while read i;do somecommandto $i;done</code></div>
<div style="margin-left:40px;">
<p>is one of the most useful I've ever found for getting something done quickly to a lot of data. For example, recovering deleted files from an ntfs dd image:</p>
<p><code>ils -rf ntfs imagefile.dd &#124; awk -F '&#124;' '($2=="f") {print $1}' &#124; while read i; do icat -rsf ntfs imagefile.dd $i &#62; ./deleted/$i; done</code></p>
<p>A quick way to sort unknown files (maybe those recovered using the command above) by type:</p>
<p><code>file * &#124; grep -i jpeg &#124; cut -f 1 -d ':' &#124; while read i; do mv "$i" jpegs; done</code></p>
<p>Not strictly using a 'while' but still useful if you need to quicklyresolve hostnames in an IP range:</p>
<p><code>for (( i=1; i&#60;=254 ; i++ )) ; do resolveip 10.0.0.$i 2&#62;/dev/null ; done &#124; grep -vi 'Unable'</code></div>
<div style="margin-left:40px;">3) Quick totals</div>
<div style="margin-left:40px;">Sort, uniq and head piped together can get you a top 10 quicker than Dave Letterman:</div>
<div style="margin-left:40px;"><code>cat filewithlotsofIPAddresses.txt &#124; egrep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" &#124; sort &#124; uniq -c &#124; sort -rn &#124; head -n10</code></div>
<div style="margin-left:40px;">
<p>will get you the top 10 IP addresses in a file sorted by appearances, highest to lowest. Not as funny as Letterman, but hey it's Linux!</p></div>
</div>
<p>No doubt if you've been around the block more than a few times you've got your own pipelines you can't live without. If you're open to it, share them so folks can pick up something new or add to their favorites.</p>
<p>Links to more info:</p>
<div style="margin-left:40px;"><a href="http://www.jonesdykstra.com/index.php/home-mainmenu-1/81-tools">pasco</a>, <a href="http://www.habets.pp.se/synscan/programs.php?prog=pipebench">pipebench</a>, <a href="http://www.nongnu.org/regex-markup/">remark</a>, <a href="http://dev.mysql.com/doc/refman/5.0/en/resolveip.html">resolveip</a>, <a href="http://www.sleuthkit.org/sleuthkit/man/ils.html">ils</a>, <a href="http://www.sleuthkit.org/sleuthkit/man/icat.html">icat</a>, <a href="http://www.gnu.org/software/grep/">grep</a>, <a href="http://www.gnu.org/software/coreutils/">sort</a>, <a href="http://www.gnu.org/software/coreutils/">uniq</a>, <a href="http://www.gnu.org/software/coreutils/">head</a>, <a href="http://www.gnu.org/software/coreutils/">tail</a>, <a href="ftp://ftp.astron.com/pub/file/">file</a> and <a href="http://www.gnu.org/software/gawk/gawk.html">awk</a></div>
<p><em>Jeff Bryner , GCFA Gold #137, also holds the CISSP and GCIH certifications, occasionally teaches for SANS and performs forensics, intrusion analysis, and security architecture work on a daily basis.</em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Unix Shell Scripting]]></title>
<link>http://irfanworld.wordpress.com/?p=59</link>
<pubDate>Tue, 16 Sep 2008 07:13:06 +0000</pubDate>
<dc:creator>Irfan</dc:creator>
<guid>http://irfanworld.pt-br.wordpress.com/2008/09/16/unix-shell-scripting/</guid>
<description><![CDATA[This post will help administrator and novice UNIX programmer to understand and write strong as well ]]></description>
<content:encoded><![CDATA[<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">This post will help administrator and novice UNIX programmer to understand and write strong as well as useful shell programs. I will talks on shell syntax and few simple day-to-day utilities for UNIX. Will discussing mainly Bourn shell because of its widely acclaimed popularity and usage among the UNIX world.</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">Many standard utilities (rdist, make, cron, etc.) allow you to specify a command to run at a certain time. Usually, this command is simply passed to the Bourne shell, which means that you can execute whole scripts, should you choose to do so. Steve Bourne, wrote the Bourne shell which appeared in the Seventh Edition Bell Labs Research version of Unix. </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">Lastly, UNIX runs Bourne shell scripts when it boots. If you want to modify the boot-time behavior of a system, you need to learn to write and modify Bourne shell scripts. It said there are 95% shell code written in Bourne shell. Code written in Bourne shell is compatible with shell scripting like ksh, bash &#38; zsh. That means with minimal or no change one could port shell script written in Bourne shell to ksh or bash or zsh.</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">*Bash is popular among Linux users. </span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">There are couple of other shells available which I will not be talking are C shell ( Used by C program to create programming rich shell) this is incompatible to Bourne shell. The C shell, csh, and its variant tcsh is a fine interactive shell (I use tcsh), but is a lousy shell for writing scripts.</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:Arial;">Lets understand what is an executable files, they also know as program or binary executables, This files are machine readable files and human eyes can not make sense out of it. Others only contain text, knows as script. They are interpreter scripts like awk, sed, perl and many more.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3><span>Learning Shell Scripting</span></h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The first line of any script must begin with #!, followed by the name of the interpreter. Some versions of UNIX allow whitespace between #! and the name of the interpreter. Others do not. Hence, if you want your script to be portable, leave out the blank.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A script, like any file that can be run as a command, needs to be executable: save this script as rotatelog and run</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">chmod +x rotatelog<br />
to make it executable.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">You can now run it by running<br />
./rotatelog</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Unlike some other operating systems, UNIX allows any program to be used as a script interpreter. This is why people talk about ``a Bourne shell script'' or ``an awk script.'' One might even write a more script, or an ls script (though the latter wouldn't be terribly useful). Hence, it is important to let Unix know which program will be interpreting the script.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">When Unix tries to execute the script, it sees the first two characters (#!) and knows that it is a script. It then reads the rest of the line to find out which program is to execute the script. For a Bourne shell script, this will be /bin/sh. Hence, the first line of our script must be</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">After the command interpreter, you can have one, and sometimes more, options. Some flavors of Unix only allow one, though, so don't assume that you can have more.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Variables</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh allows you to have variables, just like any programming languages. Variables do not need to be declared. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">To set a sh variable, use VAR=value</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">And to use the value of the variable later, use $VAR or ${VAR}</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The latter syntax is useful if the variable name immediately followed by other text:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">COLOR=yellow </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo This looks $COLORish </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo This seems ${COLOR}ish</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">prints</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This looks </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This seems yellowish</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">There is only one type of variable in sh: strings. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This is somewhat limited, but is sufficient for most purposes.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Local vs. environment variables</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A sh variable can be either a local variable or an environment variable. They both work the same way; the only difference lies in what happens when the script runs another program (which, as we saw earlier, it does all the time).</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Environment variables are passed to subprocesses. Local variables are not.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">By default, variables are local. To turn a local variable into an environment variable, </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">use</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">export VAR</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Here's a simple wrapper for a program:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">NETSCAPE_HOME=/usr/imports/libdata </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">CLASSPATH=$NETSCAPE_HOME/classes </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">export CLASSPATH $NETSCAPE_HOME/bin/netscape.bin</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Here, NETSCAPE_HOME is a local variable; CLASSPATH is an environment variable. CLASSPATH will be passed to netscape.bin (netscape.bin uses the value of this variable to find Java class files); NETSCAPE_HOME is a convenience variable that is only used by the wrapper script; netscape.bin doesn't need to know about it, so it is kept local.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The only way to unexport a variable is to unset it:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">unset VAR</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This removes the variable from the shell's symbol table, effectively making as if it had never existed; as a side effect, the variable is also unexported.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Also, if you have a function by the same name as the variable, unset will also delete that function. Since you may want to use this variable later, it is better not to define it in the first place.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Also, note that if a variable was passed in as part of the environment, it is already an environment variable when your script starts running. If there is a variable that you really don't want to pass to any subprocesses, you should unset it near the top of your script. This is rare, but it might conceivably happen.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If you refer to a variable that hasn't been defined, sh substitutes the empty string.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo aaa $FOO bbb </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo xxx${FOO}yyy</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">prints</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">aaa bbb xxxyyy</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Special variables</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh treats certain variables specially: some are set for you when your script runs, and some affect the way commands are interpreted.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Command-line arguments</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The most useful of these variables are the ones referring to the command-line arguments. $1 refers to the first command-line argument (after the name of the script), $2 refers to the second one, and so forth, up to $9.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If you have more than nine command-line arguments, you can use the shift command: this discards the first command-line argument, and bumps the remaining ones up by one position: $2 becomes $1, $8 becomes $7, and so forth.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The variable $0 (zero) contains the name of the script (argv[0] in C programs).</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Often, it is useful to just list all of the command-line arguments. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">For this, sh provides the variables $* (star) and $@ (at). Each of these expands to a string containing all of the command-line arguments, as if you had used $1 $2 $3...</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The difference between $* and $@ lies in the way they behave when they occur inside <a href="#double-quotes" target="_blank"><span style="text-decoration:none;color:#000000;">double quotes</span></a>: $* behaves in the normal way, whereas $@ creates a separate double-quoted string for each command-line argument. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">That is, "$*" behaves as if you had written "$1 $2 $3", whereas "$@" behaves as if you had written "$1" "$2" "$3".</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Finally, $# contains the number of command-line arguments that were given.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Other special variables</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">$? gives the exit status of the last command that was executed. This should be zero if the command exited normally.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">$- lists all of the options with which sh was invoked. See sh(1) for details.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">$$ holds the PID of the current process.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">$! holds the PID of the last command that was executed in the background.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">$IFS (Input Field Separator) determines how sh splits strings into words.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Quasi-variable constructs</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The ${VAR} construct is actually a special case of a more general class of constructs:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">${VAR:-expression} </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Use default value: if VAR is set and non-null, expands to $VAR. Otherwise, expands to expression. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">${VAR:=expression} </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Set default value: if VAR is set and non-null, expands to $VAR. Otherwise, sets VAR to expression and expands to expression. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">${VAR:?[expression]} </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If VAR is set and non-null, expands to $VAR. Otherwise, prints expression to standard error and exits with a non-zero exit status. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">${VAR:+expression} </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If VAR is set and non-null, expands to the empty string. Otherwise, expands to expression. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">${#VAR} </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Expands to the length of $VAR. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The above patterns test whether VAR is set and non-null. Without the colon, they only test whether VAR is set.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Pattern-matching</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh supports a limited form of pattern-matching. The operators are</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">* Matches zero or more characters. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">? Matches exactly one character. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">[range] Matches any character in range. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Range can be either a list of characters that match, or two endpoints separated by a dash: [ak3] matches either a, k, or 3; [a-z] matches any character in the range a through z; [a-mz] matches either a character in the range a through m, or z. If you wish to include a dash as part of the range, it must be the first character, e.g., [-p] will match either a dash or p. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">When an expression containing these characters occurs in the middle of a command, sh substitutes the list of all files whose name matches the pattern. This is known as ``globbing.'' Otherwise, these are used mainly in the <a href="#case" target="_blank"><span style="text-decoration:none;color:#000000;">case</span></a> construct.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">As a special case, when a glob begins with * or ?, it does not match files that begin with a dot. To match these, you need to specify the dot explicitly (e.g., .*, /tmp/.*).</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Note to MS-DOS users: under MS-DOS, the pattern *.* matches every file. In sh, it matches every file that contains a dot.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Quoting</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If you say something like</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo * MAKE $$$ FAST *</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">it won't do what you want: first of all, sh will expand the *s and replace them with a list of all the files in the current directory. Then, since any number of tabs or blanks can separate words, it will compress the three spaces into one. Finally, it will replace the first instance of $$ with the PID of the shell. This is where quoting comes in.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh supports several types of quotes. Which one you use depends on what you want to do.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Backslash</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Just as in C strings, a backslash (``\'') removes any special meaning from the character that follows. If the character after the backslash isn't special to begin with, the backslash has no effect. The backslash is itself special, so to escape it, just double it: \\.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Single quotes</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Single quotes, such as 'foo' work pretty much the way you'd expect: anything inside them (except a single quote) is quoted. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">You can say</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo '* MAKE $$$ FAST *'</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">and it'll come out the way you want it to.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Note that a backslash inside single quotes also loses its special meaning, so you don't need to double it. There is no way to have a single quote inside single quotes.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Double quotes, such as</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">"foo"</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">preserve spaces and most special characters. However, variables and <a href="#backquote" target="_blank"><span style="text-decoration:none;color:#000000;">backquoted expressions</span></a> are expanded and replaced with their value.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If you have an expression within backquotes (also known as backticks), e.g.,</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">`cmd`</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">the expression is evaluated as a command, and replaced with whatever the expression prints to its standard output. Thus,</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo You are `whoami`</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">prints</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">You are irfan</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Built-in commands</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh understands several built-in commands, i.e., commands that do not correspond to any program. These commands include:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">{ commands ; }, ( commands ) </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Execute commands in a subshell. That is, run them as if they were a single command. This is useful when <a href="#io-redirection" target="_blank"><span style="text-decoration:none;color:#000000;">I/O redirection</span></a> is involved, since you can pipe data to or from a mini-script inside a pipeline.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The { commands; } variant is somewhat more efficient, since it doesn't spawn a true subshell. This also means that if you set variables inside of it, the changes will be visible in the rest of the script. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">: (colon) </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Does nothing. This is generally seen as </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">: ${VAR:=default}</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">. filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The dot command reads in the specified filename, as if it had occurred at that place in the script. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">bg [job], fg [job] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">bg runs the specified job (or the current job, if none is specified) in the background. fg resumes the specified job (or the current job, if none is specified) in the foreground. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Jobs are specified as %number. The jobs command lists jobs. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">cd [dir] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Sets the current directory to dir. If dir is not specified, sets the current directory to the home directory. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">pwd </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Prints the current directory. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo args </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Prints args to standard output. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">eval args </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Evaluates args as a sh expression. This allows you to construct a string on the fly (e.g., using a variable that holds the name of a variable that you want to set) and execute it. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">exec command </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Runs the specified command, and replaces the current shell with it. That is, nothing after the exec statement will be executed, unless the exec itself fails. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">exit [n] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Exit the current shell with exit code n. This defaults to zero. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">kill [-sig] %job </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Send signal sig to the specified job. sig can be either numeric or symbolic. kill -l lists all available signals. By default, sig is SIGTERM (15). </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">read name... </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Reads one line from standard input and assigns it to the variable name. If several variables name1, name2, name3 etc. are specified, then the first word of the line read is assigned to name1, the second to name2, and so forth. Any remaining words are assigned to the last variable. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">set [+/-flag] [arg] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">With no arguments, prints the values of all variables.set -x turns on the x option to sh; set +x turns it off.set args... sets the command-line arguments to args.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">test expression </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Evaluates a boolean expression and exits with an exit code of zero if it is true, or non-zero if it is false. See <a href="#test" target="_blank"><span style="text-decoration:none;color:#000000;">test</span></a> for more details. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">trap [command sig]... </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If signal sig is sent to the shell, execute command. This is useful for exiting cleanly (e.g., removing temporary files etc.) when the script is interrupted. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">ulimit </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Print or set system limits on resource usage. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">umask [nnn] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Sets the umask to nnn (an octal number). With no argument, prints the current umask. This is most useful when you want to create files, but want to restrict who can read or write them. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">wait [n] </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Wait for the background process whose PID is n to terminate. With no arguments, waits for all of the background processes to terminate. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Bear in mind that the list of builtins varies from one implementation to another, so don't take this list as authoritative.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Flow control</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sh supports several flow-control constructs, which add power and flexibility to your scripts.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:14pt;font-family:Verdana;">if</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The if statement is a simple conditional. You've seen it in every programming language. Its syntax is</span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">if condition ; then<br />
commands<br />
[elif condition ; then<br />
commands]...<br />
[else<br />
commands]<br />
fi</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">That is, an if-block, optionally followed by one or more elif-blocks (elif is short for ``else if''), optionally followed by an else-block, and terminated by fi.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The if statement pretty much does what you'd expect: if condition is true, it executes the if-block. Otherwise, it executes the else-block, if there is one. The elif construct is just syntactic sugar, to let you avoid nesting multiple if statements.</span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">myname=`whoami` </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">if [ $myname = root ]; then </span></p>
<p style="margin:0 0 .0001pt 1in;"><span style="font-size:10pt;font-family:Arial;">echo "Welcome to FooSoft 3.0" </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">else </span></p>
<p style="margin:0 0 .0001pt 1in;"><span style="font-size:10pt;font-family:Arial;">echo "You must be root to run this script" </span></p>
<p style="margin:0 0 .0001pt 1in;"><span style="font-size:10pt;font-family:Arial;">exit 1 </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">fi</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The more observant among you (or those who are math majors) are thinking, ``Hey! You forgot to include the square brackets in the syntax definition!''</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Actually, I didn't: [ is actually a command, /bin/[, and is another name for the test command. See <a href="#test" target="_blank"><span style="text-decoration:none;color:#000000;">below</span></a> for details.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This is why you shouldn't call a test program test: if you have ``.'' at the end of your path, as you should, executing test will run /bin/test.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The condition can actually be any command. If it returns a zero exit status, the condition is true; otherwise, it is false. Thus, you can write things like</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">user=arnie </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">if grep $user /etc/passwd; then </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">echo "$user has an account" </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">else </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">echo "$user doesn't have an account" </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">fi</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>while</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The while statement should also be familiar to you from any number of other programming languages. Its syntax in sh is</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">while condition; do<br />
commands<br />
done</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">As you might expect, the while loop executes commands as long as condition is true. Again, condition can be any command, and is true if the command exits with a zero exit status.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A while loop may contain two special commands: break and continue.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">break exits the while loop immediately, jumping to the next statement after the done.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">continue skips the rest of the body of the loop, and jumps back to the top, to where condition is evaluated.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>for</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The for loop iterates over all of the elements in a list. Its syntax is</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">for var in list; do<br />
commands<br />
done</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">list is zero or more words. The for construct will assign the variable var to each word in turn, then execute commands. For example:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#!/bin/sh </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">for i in foo bar baz "do be do"; do </span></p>
<p style="margin:0 0 .0001pt .5in;"><span style="font-size:10pt;font-family:Arial;">echo "$i" </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">done</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">will print</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">foo bar baz do be do</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A for loop may also contain break and continue statements. They work the same way as in the while loop.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Case</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The case construct works like C's switch statement, except that it matches patterns instead of numerical values. Its syntax is</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">case expression in<br />
pattern)<br />
commands<br />
;;<br />
...<br />
esac</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">expression is a string; this is generally either a variable or a backquoted command.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">pattern is a glob pattern (see <a href="#globbing" target="_blank"><span style="text-decoration:none;color:#000000;">globbing</span></a>).</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The patterns are evaluated in the order in which they are seen, and only the first pattern that matches will be executed. Often, you'll want to include a ``none of the above'' clause; to do this, use * as your last pattern.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>IO</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A command's input and/or output may be redirected to another command or to a file. By default, every process has three file descriptors: standard input (0), standard output (1) and standard error (2). By default, each of these is connected to the user's terminal.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">However, one can do many interesting things by redirecting one or more file descriptor:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#60; filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Connect standard input to the file filename. This allows you to have a command read from the file, rather than having to type its input in by hand. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#62; filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Connect standard output to the file filename. This allows you to save the output of a command to a file. If the file does not exist, it is created. If it does exist, it is emptied before anything happens. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">(Exercise: why doesn't cat * &#62; zzzzzzz work the way you'd expect?)</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#62;&#62; filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Connects standard output to the file filename. Unlike &#62;, however, the output of the command is appended to filename. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#60;&#60;word </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This construct isn't used nearly as often as it could be. It causes the command's standard input to come from... standard input, but only until word appears on a line by itself. Note that there is no space between &#60;&#60; and word.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This can be used as a mini-file within a script, e.g., </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">cat &#62; foo.c &#60;&#60;EOT </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">#include &#60;stdio.h&#62; </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">main() { </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">printf("Hello, world!\n"); </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">} EOT</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">It is also useful for printing multiline messages, e.g.:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">line=13 cat &#60;&#60;EOT An error occurred on line $line. See page 98 of the manual for details. EOT</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">As this example shows, by default, &#60;&#60; acts like double quotes (i.e., variables are expanded). If, however, word is quoted, then &#60;&#60; acts like single quotes.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#60;&#38;digit </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Use file descriptor digit as standard input. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#62;&#38;digit </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Use file descriptor digit as standard output. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#60;&#38;- </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Close standard input. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">&#62;&#38;- </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Close standard output. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">command1 &#124; command2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Creates a pipeline: the standard output of command1 is connected to the standard input of command2. This is functionally identical to </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">command1 &#62; /tmp/foo<br />
command2 &#60; /tmp/foo</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">except that no temporary file is created, and both commands can run at the same time</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">There is a proverb that says, ``A temporary file is just a pipe with an attitude and a will to live.'' Any number of commands can be pipelined together.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">command1 &#38;&#38; command2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Execute command1. Then, if it exited with a zero (true) exit status, execute command2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">command1 &#124;&#124; command2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Execute command1. Then, if it exited with a non-zero (false) exit status, execute command2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If any of the redirection constructs is preceded by a digit, then it applies to the file descriptor with that number, rather than the default (0 or 1, as the case may be). For instance,</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">command 2&#62;&#38;1 &#62; filename</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">associates file descriptor 2 (standard error) with the same file as file descriptor 1 (standard output), then redirects both of them to filename.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">This is also useful for printing error messages:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo "Danger! Danger Will Robinson!" 1&#62;&#38;2</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Note that I/O redirections are parsed in the order they are encountered, from left to right. This allows you to do fairly tricky things, including throwing out standard output, and piping standard output to a command.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>Functions</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">When a group of commands occurs several times in a script, it is useful to define a function. Defining a function is a lot like creating a mini-script within a script.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A function is defined using</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">name () {<br />
commands<br />
}</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">and is invoked like any other command:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">name args...</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">You can redirect a function's I/O, embed it in backquotes, etc., just like any other command.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">One way in which functions differ from external scripts is that the shell does not spawn a subshell to execute them. This means that if you set a variable inside a function, the new value will be visible outside of the function.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A function can use return n to terminate with an exit status of n. Obviously, it can also exit n, but that would terminate the entire script.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Function arguments</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">A function can take command-line arguments, just like any script. Intuitively enough, these are available through $1, $2... $9 just like the main script.</span></p>
<h3>Useful utilities</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">There are a number of commands that aren't part of sh, but are often used inside sh scripts. These include:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">basename</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">basename pathname prints the last component of pathname:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">basename /foo/bar/baz</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">prints</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">baz</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">dirname</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The complement of basename: dirname pathname prints all but the last component of pathname, that is the directory part: pathname:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">dirname /foo/bar/baz</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">prints</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">/foo/bar</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">/bin/[ is another name for /bin/test. It evaluates its arguments as a boolean expression, and exits with an exit code of 0 if it is true, or 1 if it is false.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">If test is invoked as [, then it requires a closing bracket ] as its last argument. Otherwise, there must be no closing bracket.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">test understands the following expressions, among others:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-e filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-d filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists and is a directory. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-f filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists and is a plain file. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-h filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists and is a symbolic link. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-r filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists and is readable. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-w filename </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if filename exists and is writable. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-n string </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the length of string is non-zero. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">-z string </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the length of string is zero. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">string </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if string is not the empty string. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">s1 = s2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the strings s1 and s2 are identical. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">s1 != s2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the strings s1 and s2 are not identical. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -eq n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the numbers n1 and n2 are equal. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -ne n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the numbers n1 and n2 are not equal. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -gt n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the number n1 is greater than n2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -ge n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the number n1 is greater than or equal to n2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -lt n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the number n1 is less than n2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">n1 -le n2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if the number n1 is less than or equal to n2. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">! expression </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Negates expression, that is, returns true iff expression is false. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">expr1 -a expr2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if both expressions, expr1 and expr2 are true. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">expr1 -o expr2 </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">True if either expression, expr1 or expr2 is true. </span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">( expression )</span><span style="font-size:10pt;font-family:Verdana;"> </span></p>
<h3>True if expression is true. This allows one to nest expressions.</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Note that lazy evaluation does not apply, since all of the arguments to test are evaluated by sh before being passed to test. If you stand to benefit from lazy evaluation, use nested ifs.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>echo</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo is a built-in in most implementations of sh, but it also exists as a standalone command.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo simply prints its arguments to standard output. It can also be told not to append a newline at the end: under BSD-like flavors of Unix, use</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">echo -n "string"</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Under SystemV-ish flavors of Unix, use</span></p>
<p><span style="font-size:10pt;font-family:Arial;">echo "string\c"</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>awk</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Awk (and its derivatives, nawk and gawk) is a full-fledged scripting language. Inside sh scripts, it is generally used for its ability to split input lines into fields and print one or more fields. For instance, the following reads /etc/passwd and prints out the name and uid of each user:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">awk -F : '{print $1, $3 }' /etc/passwd</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The -F : option says that the input records are separated by colons. By default, awk uses whitespace as the field separator.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>sed</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Sed (stream editor) is also a full-fledged scripting language, albeit a less powerful and more convoluted one than awk. In sh scripts, sed is mainly used to do string substitution: the following script reads standard input, replaces all instances of ``foo'' with ``bar'', and writes the result to standard output:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">sed -e 's/foo/bar/g'</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The trailing g says to replace all instances of ``foo'' with ``bar'' on a line. Without it, only the first instance would be replaced.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;"> </span></p>
<h3>tee</h3>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">tee [-a] filename reads standard input, copies it to standard output, and saves a copy in the file filename.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">By default, tee empties filename before it begins. With the -a option, it appends to filename.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Debugging</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">Unfortunately, there are no symbolic debuggers such as gdb for sh scripts. When you're debugging a script, you'll have to rely the tried and true method of inserting trace statements, and using some useful options to sh:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The -n option causes sh to read the script but not execute any commands. This is useful for checking syntax.</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">The -x option causes sh to print each command to standard error before executing it. Since this can generate a lot of output, you may want to turn tracing on just before the section that you want to trace, and turn it off immediately afterward:</span></p>
<p style="margin:0 0 .0001pt;"><span style="font-size:10pt;font-family:Arial;">set -x # XXX - What's wrong with this code? grep $user /etc/passwd 1&#62;&#38;2 &#62; /dev/null set +x</span></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The Next Top 10 UNIX Good Usage habits]]></title>
<link>http://wonderingpondering.wordpress.com/?p=605</link>
<pubDate>Tue, 09 Sep 2008 03:04:43 +0000</pubDate>
<dc:creator>wonderingpondering</dc:creator>
<guid>http://wonderingpondering.pt-br.wordpress.com/2008/09/09/the-next-top-10-unix-good-usage-habits/</guid>
<description><![CDATA[This article - from my favorite Big Blue web site for UNIX documentation - spotlights 10 good usage ]]></description>
<content:encoded><![CDATA[<p>This article - from my favorite Big Blue web site for UNIX documentation - spotlights 10 good usage habits for those of us who are Unix lovers and users.</p>
<p>Actually, these are the 2nd 10, the first already documented by Michael Stutz - complete with link in the article. This set of 10 were selected to help you break the bad habit or two you have allowed to linger on. (Other than this one or two, you are a perfect programmer, and we would expect nothing else from someone as sharp and professional as you are.)</p>
<p>A couple examples - OK, all 10:</p>
<ul>
<li>Use file name completion.</li>
<li>Use history expansion.</li>
<li>Reuse previous arguments.</li>
<li>Manage directory navigation with <code>pushd</code> and <code>popd</code>.</li>
<li>Find large files.</li>
<li>Create temporary files without an editor.</li>
<li>Use the <code>curl</code> command-line utility.</li>
<li>Make the most of regular expressions.</li>
<li>Determine the current user.</li>
<li>Process data with <code>awk</code>.</li>
</ul>
<p>So now you can be perfect.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[IP von eth0 mittels ifconfig auslesen]]></title>
<link>http://nickolsen.wordpress.com/?p=57</link>
<pubDate>Tue, 02 Sep 2008 18:37:14 +0000</pubDate>
<dc:creator>nickolsen</dc:creator>
<guid>http://nickolsen.pt-br.wordpress.com/2008/09/02/ein-bash-befehl/</guid>
<description><![CDATA[Zum Auslesen der IP aus ifconfig. Geht sicher einfacher, aber mir gehts ein wenig um die Arbeit mit ]]></description>
<content:encoded><![CDATA[<p>Zum Auslesen der IP aus ifconfig. Geht sicher einfacher, aber mir gehts ein wenig um die Arbeit mit grep, awk, sed etc.</p>
<p><code><em>ifconfig eth0 &#124; grep 'inet Adresse' &#124; awk -F ':' '{ print $2 }' &#124; awk -F ' ' '{ print $1 }'</em></code><br />
Ausgabe ist einfach die IP-Adresse des Interfaces eth0.</p>
<p><code><em>ping $(ifconfig eth0 &#124; grep 'inet Adresse' &#124; awk -F ':' '{ print $2 }' &#124; awk -F ' ' '{ print $1 }')</em></code><br />
Pingt die rausgefilterte Adresse an. (Bringt zwar nicht viel, weils die eigene IP ist, aber egal :D Der Syntax-Lerneffekt zählt!)</p>
<p>Ich bin aber der Meinung, dass man vor allem das zweite <code><em>awk</em></code> schöner gestalten kann!</p>
<p><b>EDIT: </b> <code><em>ifconfig eth0 &#124; grep 'inet Adresse' &#124; awk -F ':' '{ print $2 }' &#124; awk '{ print $1 }'</em></code><br />
Find ich persönlich noch besser!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[power of scripts]]></title>
<link>http://nullpointers.wordpress.com/?p=11</link>
<pubDate>Tue, 05 Aug 2008 07:56:02 +0000</pubDate>
<dc:creator>Intensity !</dc:creator>
<guid>http://nullpointers.pt-br.wordpress.com/2008/08/05/power-of-scripts/</guid>
<description><![CDATA[around 4 months back, i started dusting off whatever bit of awk that i learnt in 1997. dint take mor]]></description>
<content:encoded><![CDATA[<p>around 4 months back, i started dusting off whatever bit of awk that i learnt in 1997. dint take more than an hour to get a decent grip and could start writing some meaningful scripts.</p>
<p>then, like how a person with hammer sees every problem as nail, I started looking out for problems that i could solve using my newly acquired weapon. there were plenty. not just problems, but could do quite  a bit of new things that would be too difficult to do with java and bit difficult with python. Above all I like awk's simplicity. After all it is written by 3 demigods (Aho, Weinberger &#38; kernighan)</p>
<p>Let me end this post by writing a few words on one of my awk exploits. In the legacy code that we have, the SQL statements are spewed all over the code. MVC has been violated to the extent possible. Whenever we add a new column to a table, we have a tough time figuring out all jsp that has code to access this table and make changes to it.</p>
<p>So I wrote an awk script that would provide such a report                                                                   1. In each jsp file, the db tables used.</p>
<p>2. For each db table, the number of jsp files that accesses this table.</p>
<p>3. In both the cases the line number and the CRUD information.</p>
<p>It is really worth spending some time learning and becoming comfortable with any scripting language. The productivity gains are enormous and it is more fun writing these scripts. In the forthcoming posts, I will write in more detail about some of the scripts.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Add include directive to awk]]></title>
<link>http://yogsototh.wordpress.com/2008/07/30/add-include-directive-to-awk/</link>
<pubDate>Wed, 30 Jul 2008 12:51:36 +0000</pubDate>
<dc:creator>yogsototh</dc:creator>
<guid>http://yogsototh.pt-br.wordpress.com/2008/07/30/add-include-directive-to-awk/</guid>
<description><![CDATA[With gawk, there exists the @include directive :
@include "fic"
But, when you work for a company whi]]></description>
<content:encoded><![CDATA[<p>With gawk, there exists the <code>@include</code> directive :<br />
<code>@include "fic"</code></p>
<p>But, when you work for a company which use a prehistoric version of awk, you could use my script (it is more a hack than a real program) :</p>
<pre>#!/usr/bin/env zsh
if (($#&#60;1)); then
    {
        echo "usage : $(basename $0) script.awk arg1 ... argN"
        echo "provide @include \"path/to/awk/file\" directive"
        echo "usefull for libraries"
    } &#62;&#38;2
    exit 1
fi

tmpScriptAwk="/tmp/$(basename $1)"

# see my blog entry about this function
function matche
{
    echo "$1" &#124; egrep "$2" &#62; /dev/null
}

# go into the same directory as the script (to find the good path)
cd $(dirname $1)

# read the script
IFS='
'
for ligne in $(cat $(basename $1) &#124; sed 's/\\/\\\\/g'); do
    # transform @include "path/to/file" by the content of path/to/file.awk
     if matche "$ligne" "^@include \".*\"" ; then
         nomFic=$(echo $ligne &#124; perl -p -e 's#\@include "(.*)"#$1#' )
        # verify if the file to include is readable
         if [ ! -r "$nomFic" ]; then
            # add the .awk prefix (as it is not necessary)
             nomFic="$nomFic.awk"
             if [ ! -r "$nomFic" ]; then
                 echo "$nomFic n'est pas accessible en lecture" &#62;&#38;2
                 exit 1
             fi
         fi
        # write the content of the included file
         cat $nomFic
     else
         echo $ligne
     fi
done &#62; $tmpScriptAwk
shift
# run the script with the argument
awk -f $tmpScriptAwk "$@"</pre>
<p>Hope this help, ;-)</p>
<div class="flockcredit" style="text-align:right;color:#CCC;font-size:x-small;">Blogged with the <a title="Flock Browser" href="http://www.flock.com/blogged-with-flock" target="_new">Flock Browser</a></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[I'm Going on Vacation! End of July Isht.]]></title>
<link>http://jpeterso.wordpress.com/?p=139</link>
<pubDate>Tue, 29 Jul 2008 20:34:19 +0000</pubDate>
<dc:creator>JP</dc:creator>
<guid>http://jpeterso.pt-br.wordpress.com/2008/07/29/im-going-on-vacation-end-of-july-isht/</guid>
<description><![CDATA[Just a quick glance at what I&#8217;ve been listening to lately:

Gnarls Barkley&#8217;s &#8220;Who]]></description>
<content:encoded><![CDATA[<p>Just a quick glance at what I've been listening to lately:</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/kTVSygNKAsg'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/kTVSygNKAsg&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Gnarls Barkley's "Who's Gonna Save My Soul".<br />
<em>I'm kinda into the fact that no one is creeped out by the little heart just walking heart, but rather is looking at it with empathy. Except well for Cee-lo.</em></p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/edUjRpkOqyI'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/edUjRpkOqyI&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Ciara's "Oh".<br />
<em>Yeah, I know she's kinda played out by this point. But it's summertime damnit. Missy and Timbaland aren't sending out enough young, talented chanteuses (ie Tweet, Aliyah, Ashanti, etc.) for me to listen to on the regular.</em></p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/3SUtW3rOkz4'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/3SUtW3rOkz4&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Rick Ross' "Everyday I'm Hustlin".</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/B3Ck4ASIl5E'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/B3Ck4ASIl5E&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Flo Rida (feat. Wil.I.Am and Fergie) "Hands in the Ayer"</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/ID_N7rv-iN8'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/ID_N7rv-iN8&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Jermaine Stewart's "We Don't Have to Take Our Clothes Off"<br />
<em>Yeah, I've got nothing. I refuse to be ashamed though-- that song is so damn catchy. It's </em>AWESOME.</p>
<p>Wondering where I'm going? Well...<br />
<span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/Mtt53rCxVhY'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/Mtt53rCxVhY&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
Andrew W K's sing-songing along to "I Love New York City" at a lecture in front of 800 students.</p>
<p>Now, what you gonna do?</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/F7FMt_5wzkA'></param><param name='wmode' value='transparent'></param><embed src='http://www.youtube.com/v/F7FMt_5wzkA&rel=0' type='application/x-shockwave-flash' wmode='transparent' width='425' height='350'></embed></object></span><br />
T.I. "Bring 'Em Out" (of course).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[sum of 'total/used/avail' space on your UNIX machine]]></title>
<link>http://xxxit.wordpress.com/?p=12</link>
<pubDate>Mon, 21 Jul 2008 10:07:13 +0000</pubDate>
<dc:creator>xxxit</dc:creator>
<guid>http://xxxit.pt-br.wordpress.com/2008/07/21/sum-of-totalusedavail-space-on-your-unix-machine/</guid>
<description><![CDATA[For some reason you might need a fast way to see the sum of the space you have (total/used/avail) on]]></description>
<content:encoded><![CDATA[<p>For some reason you might need a fast way to see the sum of the space you have (total/used/avail) on your unix machine.</p>
<p>The you can use this command:</p>
<p><code># df -k &#124; egrep -v 'kbytes&#124;proc&#124;swap&#124;mnttab&#124;fd' &#124; awk '{ SUM += $4} END { print SUM }'</code></p>
<p>Basically it will print the total space available on your machine. If you need total or used space, use $2 or $3 respectively in awk part of the command.</p>
<p>Also, if you want Mb or Gb, you can just ... { print SUM/1024/1024 }'</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[fun with awk]]></title>
<link>http://tombarta.wordpress.com/?p=61</link>
<pubDate>Sat, 12 Jul 2008 05:26:08 +0000</pubDate>
<dc:creator>tombarta</dc:creator>
<guid>http://tombarta.pt-br.wordpress.com/2008/07/12/fun-with-awk/</guid>
<description><![CDATA[I admit, I&#8217;ve been experimenting more with awk lately.  Generally, my opinion has always been,]]></description>
<content:encoded><![CDATA[<p>I admit, I've been experimenting more with <tt>awk</tt> lately.  Generally, my opinion has always been, "If it's not simple enough for <tt>#!/bin/bash</tt>, I'd rather use python/perl/ruby."  Figured I'd simplify my life by having one less flavor of syntax/regexps to worry about.</p>
<p>What a silly idea!  While Python may be great for "enterprise-class"<sup>[1]</sup> log analysis, nothing beats awk for one-liners.  Take a few examples off the top of my head...</p>
<h3>Who's trying to hack me?</h3>
<pre>
$ zcat /var/log/auth.log.*.gz  &#124; awk '$6 == "Invalid" { print $8 }' &#124; sort &#124; uniq -c &#124; sort -n -r &#124; head -n 30
     79 admin
     71 test
     52 user
     43 michael
     40 alex
     39 guest
     32 oracle
     30 www
     30 dave
     28 info
     26 sales
     25 web
     25 ben
     23 victoria
     23 paul
     23 httpd
     23 adam
     22 john
     21 shop
     21 mike
     21 ftp
     21 david
     21 caroline
     21 amanda
     20 toor
     20 server
     20 samba
     20 linux
     20 danny
     20 claire
</pre>
<p>Most interesting... Nobody bothers to try <tt>root</tt>, but apparently someone's used <tt>toor</tt> before.  Also, I see a mix of common first names as well as known linux service names (<tt>httpd</tt>, <tt>ftp</tt>, etc).  My question is... are there that many sysadmins named <tt>caroline</tt>?</p>
<h3>Where are the Bastards Coming From?</h3>
<pre>
$ zcat /var/log/auth.log.*.gz &#124; awk '$6 == "Invalid" { print $10 }' &#124; sort &#124; uniq -c &#124; sort -n -r
   5170 80.237.205.72
   1243 212.112.227.139
   1040 216.190.237.68
    336 193.137.179.181
    220 200.168.28.21
    132 222.128.249.253
     94 196.200.90.99
     64 200.105.16.242
     60 211.104.85.236
     44 61.192.163.188
     13 200.11.76.170
      6 210.100.157.9
      6 124.135.192.2
      5 222.69.93.27
      5 222.189.238.179
      3 70.97.158.195
</pre>
<p>Wow, 80.237.205.72 is a really persistent little bugger.  Upon looking closer, I see all of the attempts were on a single day.  Let's see the latency between attempts:</p>
<pre>
$ zcat /var/log/auth.log.*.gz  &#124; awk '
$6 == "Invalid" &#38;&#38; $10 == "80.237.205.72" {
    oldsec = sec;
    split($3, time, ":");
    sec = time[3] + 60 * (time[2] + 60 * time[1]);
    if (oldsec &#62; 0) {
        print sec - oldsec;
    }
}' &#124; sort -n &#124; uniq -c
    267 2
   3366 3
   1457 4
     23 5
     19 6
     15 7
      1 8
      4 9
      1 10
      5 11
      1 13
      3 14
      2 15
      2 16
      2 24
      1 44
</pre>
<p>So basically, throughout the day, every 3 seconds someone was trying to log in.</p>
<p>Anyways, I thought I would have something more interesting from <tt>awk</tt>, but this'll have to suffice.</p>
<p><i>Footnote [1] Whatever that means</i></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Liznąć awk.]]></title>
<link>http://dawozgtw.wordpress.com/?p=34</link>
<pubDate>Thu, 10 Jul 2008 22:51:12 +0000</pubDate>
<dc:creator>dawoz</dc:creator>
<guid>http://dawozgtw.pt-br.wordpress.com/2008/07/11/liznac-awk/</guid>
<description><![CDATA[ Timbaland &amp; Magoo - Cop that shit ( feat. Missy Elliot)
AWK liznąłem trochę w pierwszym seme]]></description>
<content:encoded><![CDATA[<p><img src="http://estudent.put.poznan.pl/dawid.r.wozniak/obrazki/nutka.gif" alt="" width="11" height="12" /> <strong>Timbaland &#38; Magoo - Cop that shit ( feat. Missy Elliot)</strong></p>
<p style="text-align:justify;">AWK liznąłem trochę w pierwszym semestrze studiów na Językach Formalnych, jednak wtedy nie zdawałem sobie sprawy z możliwości, jakie niesie ta maszynka i ile przy pisaniu programów w tym języku może być zabawy : ) Nie będę się rozwodził tutaj nad tym, co to jest AWK, ani dawał "miniporadnika" ( bo sami zobaczycie za chwilę ), za to odsyłam Was <a href="http://pl.wikipedia.org/wiki/AWK">tutaj</a>, znajdziecie tam dużo ciekawych informacji. Ale wracając do tematu pokażę Wam, jak można się bawić z AWK : ) Od zawsze podobały mi się <a href="http://comments.deviantart.com/emoticons">emoticony</a> na deviancie <img src="http://e.deviantart.com/emoticons/m/mib.gif" alt="m i b" /> i pomyślałem, że fajnie byłoby mieć je u siebie, nie zapisując każdej po kolei prawym klawiszem myszy. Zapisałem więc sobie źródło strony z emoticonami w pliki <strong>in.html</strong> i przejrzałem kod. Okazało się, że link do emotki znajduje się zawsze na 4. polu w wierszu. Aby wyciągnąć to pole do osobnego pliku piszemu:</p>
<blockquote>
<pre>awk '{ print $4 }' in.html &#62; krok1</pre>
</blockquote>
<p style="text-align:justify;">Teraz mamy w pliku krok1 mniej tekstu, natomiast nas interesują wszystkie niepuste linie, które zawierają mniej więcej taką wartość:</p>
<ul>
<li>src="http://e.deviantart.com/emoticons/f/film.gif"</li>
</ul>
<p style="text-align:justify;">Czyli zaczynające się od <strong>wyrażenia regularnego</strong> "src", idąc tym tropem dajemy:</p>
<blockquote>
<pre>awk '/^[src]/ {print;}' krok1 &#62; krok2</pre>
</blockquote>
<p style="text-align:justify;">Pozbyliśmy się właśnie wszystkich śmieci, które były poza linijkami nas interesującymi, dalej robimy tak:</p>
<blockquote>
<pre>awk 'gsub(/(\")&#124;(src=)/,"",$0)' krok2 &#62; krok3</pre>
</blockquote>
<p style="text-align:justify;">Śpieszę z tłumaczeniem  - <strong>gsub</strong> to funkcja która szuka wzorca w naszym przypadku jest to " (cudzysłowie) oraz "src=" i zamienia je na... no własnie na nic, więc po prostu wycina. Tak więc teraz w pliku krok3 znajdują się same linki postaci:</p>
<ul>
<li> http://e.deviantart.com/emoticons/f/film.gif</li>
</ul>
<p style="text-align:justify;">Teraz pozostaje nam już tylko ściągniecie naszych emotek : )</p>
<blockquote>
<pre>awk 'system("wget \""$0"\" ")' krok3</pre>
</blockquote>
<p style="text-align:justify;">I na ekranie pokaże się wynik pracy programu <strong>wget</strong>, po wylistowaniu katalogu ukażą się nam nasze emotikonki : ) AWK może być wykorzystywane w wielu bardzo różnych przypadkach, łączyć je można z poleceniami systemowymi oraz skryptami w bashu, co daję duuuużo możliwości. W zakładce pliki jest "skrypt" w bashu, dzięki któremu możemy zautomatyzować ten proces. : )<br />
Z tego miejsca chciałbym serdecznie podziękować ZoczuS'owi za inspirację, zaszczepienie we mnie zainteresowania do awk, cierpliwość oraz wielkrotne rozjaśnianie zawiłości awk : ) Zachęcam Was również do zainteresowania się awk, bo ja na tym na pewno nie poprzestanę.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Aggiornare i pacchetti vulnerabili di FreeBSD con un piccolo trucco]]></title>
<link>http://emanuele2.wordpress.com/?p=540</link>
<pubDate>Mon, 30 Jun 2008 21:39:11 +0000</pubDate>
<dc:creator>Emanuele Cipolla</dc:creator>
<guid>http://emanuelecipolla.net/2008/06/30/aggiornare-i-pacchetti-vulnerabili-di-freebsd-con-un-piccolo-trucco/</guid>
<description><![CDATA[Non è niente di che, in realtà; volevo trovare il modo di aggiornare automaticamente tutti i pacch]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Non è niente di che, in realtà; volevo trovare il modo di aggiornare automaticamente tutti i pacchetti che portaudit(1) classifica come vulnerabili, insieme a loro eventuali dipendenze. Questo script sembra assolvere lo scopo: se c'è un modo migliore, fatemelo sapere.</p>
<p>[sourcecode lang='python']#!/usr/local/bin/bash</p>
<p># psupgrade: Aggiorna i port rilevati come insicuri da portaudit(1) utilizzando portmanager(1).</p>
<p>me=$(basename $0)</p>
<p>awk=$(which awk)<br />
echo=$(which echo)<br />
grep=$(which grep)<br />
pkg_info=$(which pkg_info)<br />
portaudit=$(which portaudit)<br />
portmanager=$(which portmanager)<br />
sed=$(which sed)</p>
<p>for tool in $awk $echo $grep $pkg_info $portaudit $portmanager $sed; do<br />
        if [ ! -x $tool ]; then<br />
                echo "Non è possibile eseguire $me perchè manca uno dei seguenti tool:"<br />
                echo "awk\n\grep\pkg_info\nportaudit\nportmanager".<br />
                echo "Assicuratevi che siano installati in una directory del PATH di sistema prima di rieseguire lo script."<br />
                exit 1<br />
        fi<br />
done</p>
<p>echo "$me: Rilevo quali pacchetti necessitano di un aggiornamento..."<br />
packages=$($echo -n $($portaudit -a &#124; $grep "Affected package:" &#124; $awk '{print $3}'))</p>
<p>echo "$me: Riferisco i pacchetti ai port d'origine..."<br />
ports=$($echo -n $($pkg_info -o $packages &#124; $grep -A 1 "Origin:" &#124; $sed -e "s/Origin://g" -e "s/--//g"))</p>
<p>echo "$me: Lancio $portmanager..."<br />
$portmanager $ports[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[VMware: Find total disk usage of snapshots on a given LUN]]></title>
<link>http://bofe.wordpress.com/?p=2134</link>
<pubDate>Mon, 16 Jun 2008 16:08:15 +0000</pubDate>
<dc:creator>bofe</dc:creator>
<guid>http://bofe.pt-br.wordpress.com/2008/06/16/vmware-find-total-disk-usage-of-snapshots-on-a-given-lun/</guid>
<description><![CDATA[I was about to delete a ton (more on that later) of VMware ESX 3.5 snapshots in our maintenance wind]]></description>
<content:encoded><![CDATA[<p>I was about to delete a ton (more on that later) of VMware ESX 3.5 snapshots in our <a href="http://twitter.com/bofe/statuses/834919698">maintenance window</a>. (Did I mention I'm a VMware admin now?)</p>
<p>After some quick Googling, I found <a href="http://www.yellow-bricks.com/2008/01/07/delete-all-snapshots/">Delete all Snapshots</a> which made me hold off on it until I had some more information about our snapshots.  This number will just increase daily until they're committed. </p>
<p>So in order to plead a case with our SAN admin, I've got to have some information. How much space is being taken up on our LUN with regards to snapshots?</p>
<p>bash to the rescue! </p>
<p><code style="font-size:120%;">[root@host LUN] ls -laR &#124; grep delta &#124; awk '{ SUM += $5} END { print SUM/1024/1024 }'</code></p>
<p>(Watch out for apostrophes etc if pasting this.)</p>
<p>Win.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Singing paeans to Python!]]></title>
<link>http://mogadalai.wordpress.com/?p=2554</link>
<pubDate>Wed, 11 Jun 2008 04:25:03 +0000</pubDate>
<dc:creator>Guru</dc:creator>
<guid>http://mogadalai.pt-br.wordpress.com/2008/06/11/singing-paens-to-python/</guid>
<description><![CDATA[Phil Hughes does the honour (and along the way there are also some other nice comparisons &#8212; li]]></description>
<content:encoded><![CDATA[<p><a href="http://www.linuxjournal.com/content/why-python-best">Phil Hughes does the honour</a> (and along the way there are also some other nice comparisons -- like the one between C and awk+sed that I quote below):</p>
<blockquote><p>In a more "awkish" venture, my old boss who was now at a company that made microprocessor hardware emulators, asked me if I could do a project for him. They were converting from a 6809-based emulator to a 68000-based one and needed to convert thousands of lines of instruction set encode and decode tables from 6809 assembly language to C. He had estimated a month to do the task assuming it would be done in C. I did it in about three days using awk and sed.</p>
<p>...</p>
<p>So, I was now a C programmer and an awk scripter. The problem was that there was a gap in my toolset. Unlike Fortran V where I even found a way to build and execute assembly language code within the Fortran framework, if I wanted to do anything other than process characters, I had to write the code in C. In most cases this wasn't bad but sometimes 99% of a task could easily be done in a few lines of awk but would require a lot of C.</p>
<p>Well, in 1999 I had the opportunity to <a href="http://www.linuxjournal.com/article/3709">interview Guido von Rossum</a>, the father of Python. While I had already been playing with Python, my chat with Guido (a lot more than an interview) inspired me to get more serious. The interview actually addresses what is wrong with awk and Perl so I won't go into more detail here.</p>
<p>While my life in the last almost ten years has not been primarily programming, I do turn to Python as my tool of choice. Some of what I have done can be called scripting but not all. For example, I implemented a credit card processing system for Visanet (the nastiest of all possible credit card protocols) in Python. I also have done some work with Karrigell, a web framework implemented in Python.</p>
<p>Ok, I talked about awk's limitations and Guido helped me beat up Perl in the interview. Note that my default comment about Perl is that if you don't know regular expressions and UNIX/Linux shell programming, Perl is not the best way to get to knowing a scripting language. So, what's left? The obvious choice is Ruby.</p>
<p>Well, this is where my long, boring history of my Pascal experience fits in. First, let me say that I like Ruby. It is a nicely-designed and very clean language. If you don't already know Python, you should seriously give it a try. But, is it better than Python? I think not.</p>
<p>Ruby, while not really new, just hasn't done as much work as Python. Much like Pascal 30 years ago, Ruby looks good on paper. Pascal's claim to fame was that there were no surprises. Ruby's is that it is pure object oriented. Those are both good things. But, as Ruby does more heavy lifting, it seems likely to me that it will have to evolve. That is, its purity will get subverted much like the purity of Pascal did.</p>
<p>In any case, I will stick with Python. It has certainly evolved over the years but that evolution feels like taking a solid base, seeing what makes it more useful and cleanly handling the evolution. To me, Python 2.5 is easier to explain to someone that Python 1.5.2.</p></blockquote>
<p>A very interesting piece; take a look!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Remove all binaries from a directory tree]]></title>
<link>http://lookherefirst.wordpress.com/?p=61</link>
<pubDate>Wed, 04 Jun 2008 18:30:09 +0000</pubDate>
<dc:creator>Bruno</dc:creator>
<guid>http://lookherefirst.pt-br.wordpress.com/2008/06/04/remove-all-binaries-from-a-directory-tree/</guid>
<description><![CDATA[Here is a one liner that packs some serious bash punch:
rm `find . -type f -exec file &#8216;{}]]></description>
<content:encoded><![CDATA[<p>Here is a one liner that packs some serious bash punch:</p>
<p><em>rm `find . -type f -exec file '{}' \; &#124; grep -i linux &#124; awk -F: '{print $1}'`</em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Not My AWK.]]></title>
<link>http://jpeterso.wordpress.com/?p=95</link>
<pubDate>Wed, 28 May 2008 18:09:12 +0000</pubDate>
<dc:creator>JP</dc:creator>
<guid>http://jpeterso.pt-br.wordpress.com/2008/05/28/not-my-awk/</guid>
<description><![CDATA[Has anyone else noticed Andrew W.K.&#8217;s new look, and found it completely bizarre and a little u]]></description>
<content:encoded><![CDATA[<p>Has anyone else noticed <a href="http://www.andrewwk.com/">Andrew W.K.'s</a> new look, and found it completely bizarre and a little uncomfortable to look at?</p>
<p><img src="http://img.photobucket.com/albums/v519/buttered2/misc/NotMyAWK01.jpg" alt="" /><br />
<img src="http://img.photobucket.com/albums/v519/buttered2/misc/NotMyAWK02.jpg" alt="" /><br />
<!--more--><br />
<img src="http://img.photobucket.com/albums/v519/buttered2/misc/NotMyAWK03.jpg" alt="" /><br />
<img src="http://img.photobucket.com/albums/v519/buttered2/misc/NotMyAWK04.jpg" alt="" /></p>
<p>I mean what happened to the high tops, dirty white jeans, and long, flowing hair? It just caught me off guard. After googling* his new look-- I am now finding myself knee-deep in what might be an AWK conspiracy thoery. Rumor has it that WK is a "pawn/actor" being controlled by Steev Mike who may or may not be his father. Also that he may or may not be wearing a hair piece. No words.</p>
<p>See <a href="http://awilkeskrier. homestead. com/">Steev Mike</a> and his <a href="http://en.wikipedia.org/wiki/Andrew_W.K.">Wikipedia page</a> on "Multiple A.W.K.'s". How far does the rabbit hole go?!</p>
<p>I remember Andrew W. Boner.<br />
<img src="http://img.photobucket.com/albums/v519/buttered2/misc/AndrewWBoner.jpg" alt="" /><br />
Goodnight, sweet prince.</p>
<p>* Sidenote: It's almost impossible to google goggles btw. I keep getting "did you mean Google?"</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ruby vs. Awk: An uneven match?]]></title>
<link>http://guenthernoack.de/2008/05/24/rubyawk/</link>
<pubDate>Sat, 24 May 2008 19:49:29 +0000</pubDate>
<dc:creator>guenthernoack</dc:creator>
<guid>http://gnoack.pt-br.wordpress.com/2008/05/24/rubyawk/</guid>
<description><![CDATA[
Thomas played around with Awk to pretty print LaTeX tables, resulting in a &#8220;one liner&#8221; ]]></description>
<content:encoded><![CDATA[<p>
<a href="http://www.unix-ag.uni-kl.de/~fischer/blog/20080512_Pretty_printing_LaTeX_tables/">Thomas played around with Awk to pretty print LaTeX tables</a>, resulting in a "one liner" ;-) . As I'm currently learning more Ruby, I was wondering if I could do better with Ruby. So here's the result. Decide for yourselves. :-)
</p>
<p>
Awk:</p>
<pre style="border:1px #888888 solid;background-color:#88ffcc;margin:5px;padding:5px;">
awk -F '[\\t ]*([&#38;]&#124;\\\\\\\\)[\\t ]*' 'BEGIN { maxcol=0 } \
  { for (i=1; imaxcol) \
  maxcol=NF-1 } END { for (c=1; c&#60;=maxcol; ++c) { \
  colwidth[c]=0; for (r=1;rcolwidth[c]) colwidth[c]= \
  length(cell[r,c]); }; for (r=1; r&#60;=NR; ++r) { printf \
  "%s%"(colwidth[1]-length(cell[r,1]))"s", cell[r,1], ""; \
  for (c=2; c&#60;=maxcol; ++c) printf " &#38; %"colwidth[c]"s", \
  cell[r,c]; print " \\\\" } }'
</pre>
</p>
<p>
Ruby: <a href="http://www.unix-ag.uni-kl.de/~guenther/blog/latexprettyprint.rb">Full source available to play with.</a></p>
<pre style="border:1px #888888 solid;background-color:#ff88cc;margin:5px;padding:5px;">
# Splits the arrays contained in the strarr parameter into
# arrays containing the individual table cell contents.
def totable(strarr)
    strarr.map do &#124;line&#124;
      line.gsub('\\','').split('&#38;').map {&#124;s&#124; s.strip}
    end
end

# Given a two multidimensional array of strings, this method
# returns an array with the maximum string sizes of the rows
# of the original array.
def rowwidths(tbl)
    tbl.map {&#124;x&#124; x.map {&#124;y&#124; y.size}}.map {&#124;x&#124; x.max}
end

# Given an Enumerable object containing LaTeX table source code
# lines, this method returns a pretty printed version of it (in
# one single string).
def prettyprint(strarr)
    tbl = totable(strarr)
    # transpose
    transposed = tbl.transpose
    colwidths = rowwidths(transposed)
    # on the transposed table: expand rows of strings
    # to full string size
    transposed = (0...transposed.size).map do &#124;i&#124;
      transposed[i].map {&#124;x&#124; sprintf("%#{colwidths[i]}s",x)}
    end
    # transpose back
    tbl = transposed.transpose
    tbl.map {&#124;x&#124; x.join(' &#38; ') + " \\\n"}.join()
end
</pre>
</p>
<p>
It's interesting to see where you end up when pushing closures to the limit to make code more concise. No explicit looping beyond that border. Is this the limit? Can you make the code more readable without going back to for-loops?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[give me a shell]]></title>
<link>http://netcrash.wordpress.com/?p=100</link>
<pubDate>Fri, 16 May 2008 02:46:12 +0000</pubDate>
<dc:creator>Fernando André</dc:creator>
<guid>http://netcrash.pt-br.wordpress.com/2008/05/16/give-me-a-shell/</guid>
<description><![CDATA[ls -l  | awk &#8216;{ system(&#8221;chown -R &#8220;$3&#8243; &#8220;$8) }&#8217;
//cuidado com dir]]></description>
<content:encoded><![CDATA[<p>ls -l  &#124; awk '{ system("chown -R "$3" "$8) }'</p>
<p>//cuidado com directorios que contenham espaços doens't work with spaces ;</p>
<p>find /home/ -uid 0 -exec ls -l \{\} \;</p>
<p>fgrep 'gold' /var/log/ -R &#124; grep -i something</p>
<p>or regexp style search<br />
egrep '(err&#124;fail&#124;warning)' /var/log/* &#62; `date +%F`.txt</p>
<p>ls -l  &#124; sed -e 's/andre/netcrash/gi'</p>
<p>#!/usr/bin/perl</p>
<p>print "hello\n";<br />
$dir="/home/andre";<br />
if ( (!(-d $dir."/Maildir")) ){<br />
`/usr/bin/maildirmake.maildrop $dir"/Maildir"`;</p>
<p>}</p>
<p>bash<br />
[03:42:08]andre@garden:~$ for i in `seq 10`; do echo $i ; done;</p>
<p>Haven't been using cut that mutch but, also a good weapon of choice.</p>
<p><strong>Simple things that evolve to more complex tools :D</strong></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The Awakeness of Shell Scripting with AWK]]></title>
<link>http://nanotaboada.wordpress.com/?p=169</link>
<pubDate>Mon, 05 May 2008 04:50:14 +0000</pubDate>
<dc:creator>Nano Taboada</dc:creator>
<guid>http://nanotaboada.pt-br.wordpress.com/2008/05/05/the-awakeness-of-shell-scripting/</guid>
<description><![CDATA[I guess I&#8217;m getting too used to the &#8220;it&#8217;s been a while!&#8221; thingy so, awkward ]]></description>
<content:encoded><![CDATA[<p>I guess I'm getting too used to the <em>"it's been a while!"</em> <a href="http://www.urbandictionary.com/define.php?term=thingy" title="thingy">thingy</a> so, awkward title aside, let's just move straight to today's post:</p>
<p>The more I learn about <strong><a href="http://en.wikipedia.org/wiki/Awk" title="AWK - Wikipedia, the free encyclopedia">AWK</a></strong>, the more I love it. It's just that simple. I've been trying its powers a bit and came with an <em>awk-mazing</em> (and probably useless, but still exciting) five-lines (<em>sans</em> comments) cute script that emulates the most popular feature (the "-e" option) of our <a href="http://en.wikipedia.org/wiki/Good_ol'_boy" title="Good ol' boy - Wikipedia, the free encyclopedia">good ol' boy</a> <strong><a href="http://www.tomshardware.com/ucg/commands/apropos-15108.html" title="apropos for UNIX COMMON - Tom's Hardware">apropos</a></strong>.<br />
Enter lazyman!<br />
<code><strong><br />
#!/bin/bash<br />
#<br />
# lazyman.sh - displays the name section of some program’s man<br />
# page.<br />
#<br />
# DESCRIPTION<br />
# this tiny script shows the NAME section of a given program’s<br />
# manual page, displaying an output quite similar to<br />
# “apropos -e” but directly calling “man” instead of querying<br />
# against “mandb”.<br />
#<br />
params=$(echo $@ &#124; awk 'END{print NF}')<br />
case $params in<br />
    1) man $1 &#124; awk '/NAME/{getline;print}' ;;<br />
    *) echo "usage: lazyman.sh [program]" ;;<br />
esac<br />
</strong></code><br />
<a href="http://www.phrases.org.uk/meanings/350000.html" title="That's all folks!">That's all folks!</a> I hope you've enjoyed it and thanks for reading!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ferramentas de trading: o script "book"]]></title>
<link>http://faiscasdevida.wordpress.com/?p=28</link>
<pubDate>Fri, 02 May 2008 22:01:48 +0000</pubDate>
<dc:creator>Gaël</dc:creator>
<guid>http://faiscasdevida.pt-br.wordpress.com/2008/05/02/ferramentas-de-trading-o-script-book/</guid>
<description><![CDATA[Segue o script que escrevi no linux. As linguagens de programação usadas são o Bash (Bourne Advan]]></description>
<content:encoded><![CDATA[<p>Segue o script que escrevi no linux. As linguagens de programação usadas são o Bash (Bourne Advanced Shell) e o AWK, que são ótimos para pequenos desenvolvimentos rápidos.</p>
<p>Segue o código-fonte.</p>
<blockquote>
<pre>#!/bin/bash

set -- `getopt ':sgboh' $*`
stat=0
graf=0
book=0
while [ "$1" != "--" ]; do
        case "$1" in
        -s)
                stat=1
                ;;
        -g)
                graf=1
                ;;
        -b&#124;-o)
                book=1
                ;;
        -h)
                echo 'Usage: book [-s&#124;-g&#124;-b] name'
                exit
                ;;
        esac
        shift
done
shift

if [ $book -eq 0 -a $graf -eq 0 -a $stat -eq 0 ]; then stat=1 ; fi
fn="$1"
if [ ! -f ~/$fn ]; then fn=$fn.htm ; fi

awk -v stat="$stat" -v book="$book" -v graf="$graf" '
/Ofertas de Compra/ { mode=1 ; get=0 ; tb=0 }
/Ofertas de Venda/ { mode=2  ; get=0 ; tb=0 }
mode==0 { next }
/&#60;tr&#62;/ {get=1}
get==1 &#38;&#38; /td_informacoes/ {
        gsub("^M","")
        line=$0 ; gsub("\\.&#124;R\\$ *&#124;[\t ]*&#60;[^&#62;]+&#62;[ \t]*","",line)
        gsub("[ \t]+"," ",line)
        if (corr[mode,tb]=="") corr[mode,tb]=line
        else if (qt[mode,tb]=="") qt[mode,tb]=line
        else if (vl[mode,tb]=="") vl[mode,tb]=line
}
/&#60;\/tr&#62;/ {
        get=0
        if (corr[mode,tb]!="") {
                if (match(qt[mode,tb],"k")) {
                        qq=qt[mode,tb]
                        qq=substr(qq,0,length(qq-1))
                        qt[mode,tb]=qq*1000
                }
                if (match(qt[mode,tb],"M")) {
                        qq=qt[mode,tb]
                        qq=substr(qq,0,length(qq-1))
                        qt[mode,tb]=qq*1000000
                }
                if (match(qt[mode,tb],"B")) {
                        qq=qt[mode,tb]
                        qq=substr(qq,0,length(qq-1))
                        qt[mode,tb]=qq*1000000000
                }
                tb++
                bk[mode]=tb
                if (tb&#62;tm) tm=tb
        }
}
END {
        mi[1]=vl[1,0]
        mi[2]=vl[2,0]
        for (i=0;i&#60;tm;i++) {
                if (book==1) {
                        if (corr[1,i]!="") printf corr[1,i]";"qt[1,i]";"vl[1,i]";"
                        else printf ";;;"
                        if (corr[2,i]!="") printf corr[2,i]";"qt[2,i]";"vl[2,i]";"
                        else printf ";;;"
                }
                mx[1]=mx[1]+qt[1,i]*vl[1,i]
                qx[1]=qx[1]+qt[1,i]
                if (vl[1,i]&#60;mi[1] &#38;&#38; vl[1,i]&#62;0) mi[1]=vl[1,i]
                if (vl[1,i]&#62;ma[1]) ma[1]=vl[1,i]
                if (vl[2,i]&#60;mi[2] &#38;&#38; vl[2,i]&#62;0) mi[2]=vl[2,i]
                if (vl[2,i]&#62;ma[2]) ma[2]=vl[2,i]
                mx[2]=mx[2]+qt[2,i]*vl[2,i]
                qx[2]=qx[2]+qt[2,i]
                qxm=(qx[1]&#60;qx[2])?qx[1]:qx[2]
                if (book==1) print ""
        }
        qqm[1]=qqm[2]=bkm=0
        vl[2,-1]=vl[2,0]
        for (i=0;i&#60;tm;i++) {
                if (qqm[1]&#60;qxm &#38;&#38; vl[1,i]&#62;vl[1,i-1]*0.60) {
                        mim=vl[1,i]
                        bkm++
                        if (qqm[1]+qt[1,i]&#62;qxm) {
                                mxm=mxm+(qxm-qqm[1])*vl[1,i]
                                qqm[1]=qxm
                        } else {
                                mxm=mxm+qt[1,i]*vl[1,i]
                                qqm[1]=qqm[1]+qt[1,i]
                        }
                }
                if (qqm[2]&#60;qxm &#38;&#38; vl[2,i]&#60;vl[2,i-1]*1.40) {
                        mam=vl[2,i]
                        bkm++
                        if (qqm[2]+qt[2,i]&#62;qxm) {
                                mxm=mxm+(qxm-qqm[2])*vl[2,i]
                                qqm[2]=qxm
                        } else {
                                mxm=mxm+qt[2,i]*vl[2,i]
                                qqm[2]=qqm[2]+qt[2,i]
                        }
                }
        }
        qc=qv=0
        ic=iv=0
        i=1
        while (ic&#60;tm &#38;&#38; iv&#60;tm) {
                if (qc==0) {
                        qc=qt[1,ic]
                        if (qc&#62;0 &#38;&#38; vl[1,ic]&#60;cv*0.60) qc=0
                        cc=vl[1,ic]
                        ic++
                }
                if (qv==0) {
                        qv=qt[2,iv]
                        if (qv&#62;0 &#38;&#38; vl[2,iv]&#62;cc*1.40) qv=0
                        cv=vl[2,iv]
                        iv++
                }
                if (qc==0 &#124;&#124; qv==0) break;
                if (qc&#62;qv) {
                        cc=int(100*(cc*qc+cv*qv)/(qc+qv)+0.5)/100
                        if (graf==1) print i ";" qv ";" cc
                        qc=qc-qv
                        qv=0
                } else {
                        cv=int(100*(cc*qc+cv*qv)/(qc+qv)+0.5)/100
                        if (graf==1) print i ";" qc ";" cv
                        qv=qv-qc
                        qc=0
                }
                i++
        }
        mmm=mxm/(2*qxm)
        mm[1]=mx[1]/qx[1]
        mm[2]=mx[2]/qx[2]
        gm=(mx[1]+mx[2])/(qx[1]+qx[2])
        if (stat==1) {
                print "-------------"
                printf("          Media    Min    Max Quantidade        Valor Ordens\n")
                printf("Compra:  %6.2f %6.2f %6.2f %10d %12d %6d\n",mm[1],mi[1],ma[1],qx[1],mx[1],bk[1])
                printf("Venda:   %6.2f %6.2f %6.2f %10d %12d %6d\n",mm[2],mi[2],ma[2],qx[2],mx[2],bk[2])
                printf("Geral:   %6.2f %6.2f %6.2f %10d %12d %6d\n",gm,mi[1],ma[2],qx[1]+qx[2],max[1]+mx[2],bk[1]+bk[2])
                printf("Melhor:  %6.2f %6.2f %6.2f %10d %12d %6d\n",mmm,mim,mam,2*qxm,mxm,bkm)
                printf("Media:   %6.2f\n",(mm[1]+mm[2])/2)
        }
}
' ~/$fn
</pre>
</blockquote>
<p>Eu não vou entrar nos detalhes de programação, mas o programa efetua o seguinte tratamento:</p>
<ol>
<li>Ele analisa um página web (.htm) contendo os dados do book de oferta, página formatada pela corretora ABN AMRO, e salva no navegador (firefox no caso, mas a opção também existe no Internet Explorer). Só interessa a página, então não precisa salvar as imagens e outros arquivos anexos.<br />
A partir dessa página, ele extrai a lista de ordens de compra e venda.</li>
<li>Se a opção -b é dada na linha de comanda (ex: book -b rdcd3), a lista de ordens é mostrada, num formato importável no excel (6 colunas: banco comprador, nº de ações, valor, banco vendedor, nº de ações, valor; o separador é o ponto-virgula; os separadores de milhares estão removidos, e os fatores (k[ilo],M[ilhão],B[ilhão]) são convertidos para só sobrar números)</li>
<li>Se a opção -s é informada (ou se nenhuma opção é dada), o programa gera algumas estatísticas:<br />
- Media, Mínimo, máximo, quantidade e valor total das ofertas de compra<br />
- Media, Mínimo, máximo, quantidade e valor total das ofertas de venda<br />
- Media, Mínimo, máximo, quantidade e valor total das ofertas<br />
- Mesma coisa, mas só satisfazendo o número de transações possíveis de acordo com a demanda e a oferta (se tiver só 100 ações para vender e 2000 para comprar, só se trocaram 100...)<br />
- Media entre a media de compra e a media de venda</li>
<li>Enfim se a opção -f for especificada, o programa gera uma lista de transações possíveis (número da transação;número de ações;valor) baseada no seguinte raciocínio: efetuamos a correspondência entre a melhor oferta de compra e a melhor oferta de venda, calculando o preço ponderado e efetuando a troca do número possível de ações. Com o que sobra para comprar ou vender, consideramos o novo preço e correspondemos com a próxima melhor venda ou compra, e assim em seguinte... Isso nós da uma lista de transações prováveis. Como podem entrar outras ofertas no intervalo, essa estimativa deve ser considerada mais como uma tendência que como uma previsão, mas dá para pegar o resultado e grafar com o excel...</li>
</ol>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Linux: Convert a Text File to Upper Case Letter]]></title>
<link>http://acrph.wordpress.com/?p=10</link>
<pubDate>Sat, 26 Apr 2008 23:01:40 +0000</pubDate>
<dc:creator>acrph</dc:creator>
<guid>http://acrph.pt-br.wordpress.com/2008/04/26/linux-convert-a-text-file-to-upper-case-letter/</guid>
<description><![CDATA[awk &#8216;{ print toupper($0) }&#8217; input_file &gt; output_file
]]></description>
<content:encoded><![CDATA[<p>awk '{ print toupper($0) }' input_file &#62; output_file</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Bash History Stats]]></title>
<link>http://lfeng1013.wordpress.com/?p=113</link>
<pubDate>Sat, 12 Apr 2008 20:34:21 +0000</pubDate>
<dc:creator>Leon Feng</dc:creator>
<guid>http://lfeng1013.pt-br.wordpress.com/2008/04/12/bash-history-stats/</guid>
<description><![CDATA[Joining the fun&#8230;
[leon@logos ~]$ history | awk &#8216;{a[$2]++} END {for(i in a){print a[i] ]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Joining <a href="http://jimmac.musichall.cz/log/?p=427">the fun</a>...</p>
<p style="text-align:justify;"><code>[leon@logos ~]$ history &#124; awk '{a[$2]++} END {for(i in a){print a[i] " " i}}' &#124; sort -nr &#124; head<br />
1504 sudo<br />
611 ls<br />
502 pacman<br />
462 cd<br />
182 vi<br />
172 mv<br />
154 rm<br />
148 man<br />
127 echo<br />
47 rename</code></p>
<p style="text-align:justify;">Now... trying to understand that evil-looking mess <img class="alignnone size-full wp-image-114" src="http://lfeng1013.wordpress.com/files/2008/04/27.gif" alt="" width="20" height="20" /> First, <code>history</code> prints out the command history in the format <code>&#60;No.&#62;  &#60;Command&#62;</code>.  Then the output is pipelined to <code>awk</code>.  <code>a[$2]</code> takes the 2nd field of the output, the commands, and stores them in an array called <code>a[]</code> as indices.  That's right... indices can be strings in awk.  See <a href="http://www.gnu.org/software/gawk/manual/gawk.html#Array-Intro">the GNU Awk User's Guide</a>.  <code>++</code> adds 1 to a command's corresponding element each time that command is encountered.  So the structure of <code>a[]</code> will look like this:</p>
<p style="padding-left:30px;text-align:justify;"><code>index           element<br />
ls              611<br />
cd              462<br />
vi              182</code></p>
<p style="text-align:justify;">After everything is processed, the <code>END</code> block prints out the whole array, with indices and elements seperated by a whitespace.  <code>sort</code> rearranges the output so the biggest numbers come up first.  Finally <code>head</code> crops the output to the first 10 lines.</p>
<p style="text-align:justify;">It's quite interesting looking at my own results.  I use <code>sudo</code> almost twice as often as <code>ls</code>. And I don't remember using <code>echo</code> that much...</p>
<p style="text-align:justify;">Note, however, this result is an incomplete statistics.  Because <code>awk '{a[$2]++}...'</code> uses whitespaces as delimiter and therefore only picks up the first word of a command line and throws the rest away.  As a result commands following a pipe or inside a parameter substitution are ignored.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Comparando versiones]]></title>
<link>http://ismaell.wordpress.com/?p=10</link>
<pubDate>Sat, 12 Apr 2008 06:26:37 +0000</pubDate>
<dc:creator>Ismael Luceno</dc:creator>
<guid>http://ismaell.pt-br.wordpress.com/2008/04/12/comparando-versiones/</guid>
<description><![CDATA[Luego de leer una nota sobre comparar versiones en la lista de correos de SourceMage, decidí buscar]]></description>
<content:encoded><![CDATA[<p>Luego de leer una nota sobre comparar versiones en la lista de correos de SourceMage, decidí buscar métodos para comparar versiones, y la primera cosa que se me vino a la mente fué usar un simple shell-script, lamentablemente el tema es un poco más complicado que eso, y no resultó muy práctico que digamos.</p>
<p>Luego de discutir sobre el tema por un rato con FCR, sugirió hacer algo muy sucio con ls -v, así que recordé que ls usa la función strverscmp() de glibc, lamentablemente no es estándar, y hacer un programa en C para esto no me hacía mucha gracia, así que decidí remangarme e implementar algo similar en AWK:</p>
<p>[sourcecode language='jscript']<br />
#!/bin/awk -f<br />
BEGIN {<br />
	FS = "[-_.]"<br />
	la = split(ARGV[1], a)<br />
	lb = split(ARGV[2], b)<br />
  	l = (la < lb) ? la : lb<br />
	o = la - lb</p>
<p>	for (i = 1; i <= l; i++) {<br />
		if (a[i] != b[i]) {<br />
			o = a[i] - b[i]<br />
			break<br />
		}<br />
	}</p>
<p>	print o<br />
}<br />
[/sourcecode]</p>
<p>¿No es hermoso?</p>
]]></content:encoded>
</item>

</channel>
</rss>
