<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Unix Tutorial &#187; Scripts</title>
	<atom:link href="http://www.unixtutorial.org/category/unix/scripts/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.unixtutorial.org</link>
	<description>Learn UNIX</description>
	<lastBuildDate>Wed, 03 Mar 2010 22:55:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fixed calculations in Unix scripts</title>
		<link>http://www.unixtutorial.org/2009/06/fixed-point-calculations-in-unix-scripts/</link>
		<comments>http://www.unixtutorial.org/2009/06/fixed-point-calculations-in-unix-scripts/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 12:11:06 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>
		<category><![CDATA[bc command]]></category>
		<category><![CDATA[calculations]]></category>
		<category><![CDATA[unix scripts]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=583</guid>
		<description><![CDATA[Although I've already shown you how to sum numbers up in bash, I only covered the bash way of doing it. I really like scripting with bash, but when it comes to calculations, there's quite a few important features missing from bash, and fixed point (thanks for the correction, Azrael Tod!) calculations is one of [...]]]></description>
			<content:encoded><![CDATA[<p>Although I've already <a title="arithmetic operations in Unix" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">shown you how to sum numbers up in bash</a>, I only covered the bash way of doing it. I really like scripting with bash, but when it comes to calculations, there's quite a few important features missing from bash, and fixed point (thanks for the correction, <a href="http://g33ky.de/">Azrael Tod</a>!) calculations is one of them. Fortunately, <strong>bc command</strong> comes as a standard in most Unix distros, and can be used for quite complex calculations.</p>
<h3>Basic calculations with bc</h3>
<p><strong>bc </strong>is a very simple command. It takes standard input as an expression and then evaluates this, performing all the necessary calculations and showing you the result. Thus, to quickly sum numbers up or get a result of some other calculation, simply echo the expression and then pipe it out to the <strong>bc command</strong>:</p>
<pre>ubuntu$ <strong>echo "1+2" | bc</strong>
3</pre>
<p>Now, in scripts your calculations with <strong>bc </strong>are done quite similarly to what we did in <strong>bash</strong>. Here's an example:</p>
<pre>ubuntu$ <strong>NUMBER1=1</strong>
ubuntu$ <strong>NUMBER2=2</strong>
ubuntu$ <strong>SUM=$(echo "$NUMBER1+$NUMBER2"| bc)</strong>
ubuntu$ <strong>echo $SUM</strong>
3</pre>
<p>I told you these calculations would be basic, right? Now onto the more interesting stuff!</p>
<h3>Fixed point calculations with bc</h3>
<p>Most people learn about bash math limitations when they attempt to do a simple calculation but can't get the current answer with fixed point values. By default, all the operations happen with integers, and that's what you would get:</p>
<pre>ubuntu$ <strong>echo "1/2" | bc</strong>
0</pre>
<p>Now, if you expect 0.5 to be the result of dividing 1 by 2, you need to explain it to <strong>bc</strong>, because by default it doesn't show you any fractional part of the number.</p>
<p>The way you do this is quite simple: all you have to do is specify the number of digits you'd like to see  after the radix point of your result. For example, if I set this number to 5, I'll get <strong>bc </strong>to output the result of my calculation with 5 digits after the radix point. The special keyword to convey this intention to the <strong>bc</strong> command is called <strong>scale</strong>. Just specify the scale value and separate it from the rest of your expression by the semicolon sign:</p>
<pre>ubuntu$ <strong>echo "scale=5; 1/2" | bc</strong>
.50000</pre>
<p>Here's another example:</p>
<pre>ubuntu$ <strong>echo "scale=5; 0.16*10.79" | bc</strong>
1.7264</pre>
<p>Hope this answers your question! <strong>bc command</strong> is very powerful, so I'll definitely have to revisit it again in the future. For now though, enjoy the fixed point calculations and be sure to ask questions if you think I can help!</p>
<h3>See also:</h3>
<ul>
<li><strong><a title="summing numbers up" href="http://www.unixtutorial.org/2009/02/unix-scripts-how-to-sum-numbers-up/">Summing numbers up in Unix scripts</a></strong></li>
<li><strong><a title="basic unix math" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">Basic math in Unix scripting</a></strong></li>
<li><strong><a title="unix scripts calculations" href="http://www.unixtutorial.org/2008/09/math-expressions-in-unix-scripts/">Another way of doing calculations in scripts</a><br />
</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2009/06/fixed-point-calculations-in-unix-scripts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unix scripts: how to sum numbers up</title>
		<link>http://www.unixtutorial.org/2009/02/unix-scripts-how-to-sum-numbers-up/</link>
		<comments>http://www.unixtutorial.org/2009/02/unix-scripts-how-to-sum-numbers-up/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 15:33:48 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=465</guid>
		<description><![CDATA[If you're ever thought of summing up more than two numbers in shell script, perhaps this basic post will be a good start for your Unix scripting experiments.
Basic construction for summing up in shell scripts
In my Basic arithmetic operations in Unix shell post last year, I've shown you how to sum up two numbers:
SUM=$(($NUMBER1 + [...]]]></description>
			<content:encoded><![CDATA[<p>If you're ever thought of summing up more than two numbers in shell script, perhaps this basic post will be a good start for your Unix scripting experiments.</p>
<h3>Basic construction for summing up in shell scripts</h3>
<p>In my <a title="arithmetic operatics in Unix" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">Basic arithmetic operations in Unix shell</a> post last year, I've shown you how to sum up two numbers:<strong></strong></p>
<pre>SUM=$(($NUMBER1 + $NUMBER2)</pre>
<p>using the same approach, it's possible to calculate sums of as many numbers as you like, if you use one of the loops available in your shell.</p>
<p>Before we get started, let's create a simple file with numbers we'll work with:</p>
<pre>ubuntu$ <strong>for i in 1 2 3 4 5 6 7 8 9; do echo $i &gt;&gt; /tmp/nums; done;</strong>
ubuntu$ <strong>cat /tmp/nums</strong>
1
2
3
4
5
6
7
8
9</pre>
<h3>Using a while loop to sum numbers up in Unix</h3>
<p>Here's an example of how you can use a <strong>while loop</strong> in Unix shell for summing numbers up. Save it as a<strong> /tmp/sum.sh</strong> script, and don't forget to do <strong>chmod a+x /tmp/sum.sh</strong> so that you can run it!</p>
<pre>#!/bin/sh
#
SUM=0
#
while read NUM
do
        echo "SUM: $SUM";
        SUM=$(($SUM + $NUM));
        echo "+ $NUM: $SUM";
done &lt; /tmp/nums</pre>
<p>Here's how the output will look when you run it:</p>
<pre>ubuntu$ <strong>/tmp/sum.sh
</strong>SUM: 0
+ 1: 1
SUM: 1
+ 2: 3
SUM: 3
+ 3: 6
SUM: 6
+ 4: 10
SUM: 10
+ 5: 15
SUM: 15
+ 6: 21
SUM: 21
+ 7: 28
SUM: 28
+ 8: 36
SUM: 36
+ 9: 45</pre>
<p>Of course, your data will most probably will be in a less readable form, so you'll have to do a bit of parsing before you get to sum the numbers up, but the loop will be organized in the same way.</p>
<p>That's it for today, enjoy and feel free to ask questions!</p>
<h3>See also:</h3>
<ul>
<li><strong><a title="arithmetics in scripts" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">Basic arithmetics in scripts</a></strong></li>
<li><strong><a title="unix shell variables" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Variables in Unix shells</a></strong></li>
<li><strong><a title="unix glossary" href="http://www.unixtutorial.org/glossary">Unix glossary</a><br />
</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2009/02/unix-scripts-how-to-sum-numbers-up/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Easy date calculations in Unix scripts with GNU date</title>
		<link>http://www.unixtutorial.org/2008/09/easy-date-calculations-in-unix-scripts-with-gnu-date/</link>
		<comments>http://www.unixtutorial.org/2008/09/easy-date-calculations-in-unix-scripts-with-gnu-date/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 13:53:10 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=107</guid>
		<description><![CDATA[When I was writing a post about using date command to confirm date and time in your Unix scripts, I made a note in my future posts list to cover the date calculations &#8211; finding out the date of yesterday or tomorrow, and so on. Today I'll show you the simplest way to calculate this.

GNU [...]]]></description>
			<content:encoded><![CDATA[<p>When I was writing a post about <a title="time and date in Unix" href="http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/">using date command to confirm date and time in your Unix scripts</a>, I made a note in my future posts list to cover the date calculations &#8211; finding out the date of yesterday or tomorrow, and so on. Today I'll show you the simplest way to calculate this.</p>
<h3></h3>
<h3>GNU date command advantage</h3>
<p>GNU version of the <strong>date</strong> command, although supporting a common syntax, has one great option: it allows you to specify the desired date with a simple string before reporting it back. What this means is that by default this specified date is assumed to be "now", but you can use other keywords to shift the result of the date command and thus show what date it was yesterday or a week ago:</p>
<p>Here's a default <strong>date</strong> output for the current date and time:</p>
<pre>ubuntu$ <strong>date</strong>
Fri Sep 19 08:06:41 CDT 2008</pre>
<p>Now, the parameter for specifying desired date is <strong>-d</strong> or <strong>&#8211;date</strong>, and if you use it with the "now" or "today" parameter, you'll get similar output:</p>
<pre>ubuntu$ <strong>date -d now</strong>
Fri Sep 19 08:06:44 CDT 2008
ubuntu$ <strong>date -d today</strong>
Fri Sep 19 08:06:50 CDT 2008</pre>
<h3>Showing tomorrow's date</h3>
<p>Similarly, you can get tomorrow's date:</p>
<pre>ubuntu$ <strong>date -d tomorrow</strong>
Sat Sep 20 08:02:12 CDT 2008</pre>
<p>Obviously, if you feel like specifying a format for the date, you can do it:</p>
<pre>ubuntu$ <strong>date -d tomorrow "+%b %d, %Y"</strong>
Sep 20, 2008</pre>
<h3>Find out yesterday's date</h3>
<p>Again, there's no rocket science involved in showing yesterday's date neither:</p>
<pre>ubuntu$ <strong>date -d yesterday "+%b %d, %Y"</strong>
Sep 18, 2008</pre>
<h3>Show a date few days away</h3>
<p>If you're interested in a certain date a few days or even weeks away, here's how you can do it:</p>
<h4>Example 1: a date 5 days ago</h4>
<pre>ubuntu$ <strong>date -d "-5 days"</strong>
Sun Sep 14 08:45:57 CDT 2008</pre>
<h4>Example 2: a day 2 weeks from now</h4>
<pre>ubuntu$ <strong>date -d "2 weeks"</strong>
Fri Oct  3 08:45:08 CDT 2008</pre>
<h4>Example 3: a day two weeks ago from now</h4>
<pre>ubuntu$ <strong>date -d "-2 weeks"</strong>
Fri Sep  5 08:45:11 CDT 2008</pre>
<h4>Extreme example: a day 50 years ago</h4>
<p>If you're really curious about dates in Unix, you can even make GNU date go back a few years:</p>
<pre>ubuntu$ <strong>date -d "-50 years"</strong>
Fri Sep 19 08:47:51 CDT 1958</pre>
<p>That's it for today, hope you like this little discovery &#8211; having mostly worked with Solaris systems most of my career, I didn't know my Ubuntu had this functionality bonus. Really useful!</p>
<h3>See also:</h3>
<ul>
<li><strong><a title="Unix date" href="http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/">Time and date in Unix scripts</a></strong></li>
<li><strong><a title="shell scripting - variables" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Variables in Unix shell scripts</a><br />
</strong></li>
<li><strong><a title="updating variables" href="http://www.unixtutorial.org/2008/08/updating-values-of-your-shell-variables-in-unix/">Updating shell variables in Unix</a><br />
</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/09/easy-date-calculations-in-unix-scripts-with-gnu-date/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Another way to use math expressions in shell scripts</title>
		<link>http://www.unixtutorial.org/2008/09/math-expressions-in-unix-scripts/</link>
		<comments>http://www.unixtutorial.org/2008/09/math-expressions-in-unix-scripts/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 00:43:06 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=105</guid>
		<description><![CDATA[Today I'd like to expand a bit more on the basic calculations in Unix scripts.
Use Parenthesis to simplify math expressions
In Basic Arithmetic Operations post I've shown you how expression evaluation can be used to calculate simple math expressions in your Unix shell:
ubuntu$ START=1
ubuntu$ FINISH=10
ubuntu$ ELAPSED=$(($FINISH - $START))
ubuntu$ echo $ELAPSED
9
Although this approach looks clean enough, there's [...]]]></description>
			<content:encoded><![CDATA[<p>Today I'd like to expand a bit more on the basic calculations in Unix scripts.</p>
<h3>Use Parenthesis to simplify math expressions</h3>
<p>In <a title="Basic arithmetic operations in scripts" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">Basic Arithmetic Operations post</a> I've shown you how expression evaluation can be used to calculate simple math expressions in your Unix shell:</p>
<pre>ubuntu$ <strong>START=1</strong>
ubuntu$ <strong>FINISH=10</strong>
ubuntu$ <strong>ELAPSED=$(($FINISH - $START))</strong>
ubuntu$ <strong>echo $ELAPSED</strong>
9</pre>
<p>Although this approach looks clean enough, there's a way to simplify it even further if you put everything in parenthesis. In other words, the same result (ELAPSED receiving a correct value of FINISH value minus START value) can be achieved this way:</p>
<pre>ubuntu$ <strong>((ELAPSED=FINISH-START))</strong>
ubuntu$ <strong>echo $ELAPSED</strong>
9</pre>
<p>It's a matter of preference, and I used to always do such calculations the former way shown, but now that one of the readers of this blog pointed out the latter way of using it, I think I might change my habits &#8211; I actually like this way much better.</p>
<h3>See also:</h3>
<ul>
<li><strong><a title="Unix Scripts: time and date" href="http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/">Time and date in Unix scripts</a></strong></li>
<li><strong><a title="Variables in Unix scripts" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Using variables in scripts</a><br />
</strong></li>
<li><strong><a title="Basic math in scripts" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Basic math in Unix scripts</a></strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/09/math-expressions-in-unix-scripts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Updating Values of Your Shell Variables in Unix</title>
		<link>http://www.unixtutorial.org/2008/08/updating-values-of-your-shell-variables-in-unix/</link>
		<comments>http://www.unixtutorial.org/2008/08/updating-values-of-your-shell-variables-in-unix/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 14:37:25 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=67</guid>
		<description><![CDATA[If you're just getting started with your Unix scripting or new to Unix shell, today's little tip will make your life much easier: I'm going to show you how to update your shell variables.
Updating shell variable in Unix
If you have a text variable in your script and would like to append some text to it [...]]]></description>
			<content:encoded><![CDATA[<p>If you're just getting started with your Unix scripting or new to Unix shell, today's little tip will make your life much easier: I'm going to show you how to update your shell variables.</p>
<h3>Updating shell variable in Unix</h3>
<p>If you have a text variable in your script and would like to append some text to it or somehow process this value, it's perfectly normal to reuse the current variable value using a syntax like this:</p>
<pre>ubuntu$ <strong>echo $VAR1</strong>
hello
ubuntu$ <strong>VAR1=$VAR1" world!"</strong>
ubuntu$ <strong>echo $VAR1</strong>
hello world!</pre>
<p>You see? It's this easy!</p>
<h3>Common cases of reusing variable values in Unix shells</h3>
<p>Most frequently, I use the technique described above to update some of my environment variables. I'm sure you'll find them useful too.</p>
<h4>Updating the PATH variable</h4>
<p><strong>PATH </strong>is the user environment variable responsible for the directories where Unix shell looks for executable commands every time you type something. Quite often you get a "file not found" error not because there isn't such a command installed in your OS, but simply because your PATH variable has not a corrept path to a directory with that command.</p>
<p>Here's an example from a standard user on one of my Red Hat Enterprise Linux systems.</p>
<p>I like the <a title="runlevel command" href="http://www.unixcommand.org/runlevel"><strong>runlevel</strong></a> command, it's quite simple and can be useful in scripts. When I attempt to run it, here's what happens:</p>
<pre>redhat$ <strong>runlevel</strong>
bash: runlevel: command not found</pre>
<p>Like I said earlier, it's most likely because my PATH variable doesn't have the /sbin directory which is where this command resides. Let's confirm this:</p>
<pre>redhat$ <strong>echo $PATH</strong>
/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin</pre>
<p>Now it's time to update the PATH and append the /sbin path to it:</p>
<pre>redhat$ <strong>PATH=$PATH:/sbin</strong></pre>
<p><a title="runlevel" href="http://www.unixtutorial.org/commands/runlevel">runlevel command</a> will be found now and here's a proof:</p>
<pre>redhat$ <strong>runlevel</strong>
N 5</pre>
<h4>Updating the MANPATH variable</h4>
<p>Another good example is the <strong>MANPATH </strong>variable, which contains the list of directories with manpages which <a title="unix man command" href="http://www.unixtutorial.org/commands/man"><strong>man command</strong></a> uses.</p>
<p>If some command doesn't have its man page in neither of the directories specified by MANPATH, you'll get an error.</p>
<p>Here's an example from one of the Solaris systems, I'm looking for a Veritas vxprint command man page:</p>
<pre>solaris$ <strong>man vxprint</strong>
No manual entry for vxprint.
solaris$ <strong>echo $MANPATH</strong>
/usr/man:/opt/sfw/man:/usr/perl5/man</pre>
<p>Let's add the /opt/VRTS/man to the MANPATH variable:</p>
<pre>bash-2.03# <strong>MANPATH=$MANPATH:/opt/VRTS/man</strong>
solaris$ <strong>echo $MANPATH</strong>
/usr/man:/opt/sfw/man:/usr/perl5/man:/opt/VRTS/man</pre>
<p>It's bound to work now:</p>
<pre>solaris$ <strong>man vxprint</strong>
Reformatting page.  Please Wait... done
...</pre>
<p>That's all I wanted to share with you today. Hope you liked the tip, and as always &#8211; feel free to ask any questions!</p>
<h3>See also:</h3>
<ul>
<li><strong><a title="environment variables" href="http://www.unixtutorial.org/2008/07/environment-variables-in-unix/">Environment variables in Unix</a></strong></li>
<li><strong><a title="Variables in Unix scripts" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Using variables in shell scripts</a></strong></li>
<li><strong><a title="arithmetic operations in Unix" href="http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/">Unix scripts: basic arithmetic operations</a><br />
</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/08/updating-values-of-your-shell-variables-in-unix/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Parse Text Files Line by Line in Unix scripts</title>
		<link>http://www.unixtutorial.org/2008/08/how-to-parse-text-files-line-by-line-in-unix-scripts/</link>
		<comments>http://www.unixtutorial.org/2008/08/how-to-parse-text-files-line-by-line-in-unix-scripts/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 16:40:38 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Questions & Answers]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Solaris]]></category>
		<category><![CDATA[Unix]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=62</guid>
		<description><![CDATA[I'm finally back from my holidays and thrilled to be sharing next of my Unix tips with you!
Today I'd like to talk about parsing text files in Unix shell scripts. This is one of the really popular areas of scripting, and there's a few quite typical limitations which everyone comes across.
Reading text files in Unix [...]]]></description>
			<content:encoded><![CDATA[<p>I'm finally back from my holidays and thrilled to be sharing next of my Unix tips with you!</p>
<p>Today I'd like to talk about parsing text files in Unix shell scripts. This is one of the really popular areas of scripting, and there's a few quite typical limitations which everyone comes across.</p>
<h3>Reading text files in Unix shell</h3>
<p>If we agree that by "reading a text file" we assume a procedure of going through all the lines found in a clear text file with a view to somehow process the data, then <a title="unix cat" href="http://www.unixtutorial.org/commands/cat/"><strong>cat command</strong></a> would be the simplest demonstration of such procedure:</p>
<pre>redhat$ <strong>cat /etc/redhat-release</strong>
Red Hat Enterprise Linux Client release 5 (Tikanga)</pre>
<p>As you can see, there's only one line in the <strong>/etc/redhat-release</strong> file, and we see what this line is.</p>
<p>But if you for whatever reason wanted to read this file from a script and assign the whole release information line to a Unix variable, using cat output would not work as expected:</p>
<pre>bash-3.1$ <strong>for i in `cat /etc/redhat-release`; do echo $i; done;</strong>
RedHat
Enterprise
Linux
Client
release
5
(Tikanga)</pre>
<p>Instead of reading a line of text from the file, our one-liner splits the line and outputs every word on a separate line of the output. This happens because of the shell syntax parsing &#8211; Unix shells assume space to be a delimiter of various elements in a list, so when you do a for loop, Unix shell interpreter treats each line with spaces as a list of elements, splits it and returns elements one by one.</p>
<h3>How to read text files line by line</h3>
<p>Here's what I decided: if I can't make Unix shell ignore the spaces between words of each line of text, I'll disguise these spaces. Since my solution was getting pretty bulky for a one-liner, I've made it into a script. Here it is:</p>
<pre>bash-3.1$ <strong>cat /tmp/cat.sh</strong>
#!/bin/sh
FILE=$1
UNIQUE='-={GR}=-'
#
if [ -z "$FILE" ]; then
        exit;
fi;
#
for LINE in `sed "s/ /$UNIQUE/g" $FILE`; do
        LINE=`echo $LINE | sed "s/$UNIQUE/ /g"`;
        echo $LINE;
done;</pre>
<p>As you can see, I've introduced an idea of a UNIQUE variable, something containing a unique combination of characters which I can use to replace spaces in the original string. This variable needs to be a unique combination in a context of your text files, because later we turn the string back into its original version, replacing all the instances of $UNIQUE text with plain spaces.</p>
<p>Since most of the needs of mine required such functionality for a relatively small text files, this rather expensive (in terms of CPU cycles) approach proved to be quite usable and pretty fast.</p>
<p><strong>Update: </strong>please see comments to this post for a much better approach to the same problem. Thanks again, Nails!</p>
<p>Here's how my script would work on the already known <strong>/etc/redhat-release</strong> file:</p>
<pre>bash-3.1$ <strong>/tmp/cat.sh /etc/redhat-release</strong>
Red Hat Enterprise Linux Client release 5 (Tikanga)</pre>
<p>Exactly what I wanted! Hopefully this little trick will save some of your time as well. Let me know if you like it or know an even better one yourself!</p>
<h3>Related books</h3>
<p>If you want to learn more, here's a great book:</p>
<div id="attachment_363" class="wp-caption aligncenter" style="width: 160px"><a href="http://www.amazon.com/gp/product/0596005954?ie=UTF8&#038;tag=unixtutorial-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0596005954"><br />
<img class="size-full wp-image-379" title="classic-shell-scripting" src="http://www.unixtutorial.org/images/classic-shell-scripting.jpg" alt="classic-shell-scripting" width="150" height="150" /></a><p class="wp-caption-text">Classic Shell Scripting</p></div>
<h3>See also:</h3>
<ul>
<li><strong><a title="Unix variables" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Using variables in scripts</a></strong></li>
<li><strong><a title="Time and date in Unix" href="http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/">Unix scripting: time and date</a></strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/08/how-to-parse-text-files-line-by-line-in-unix-scripts/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Unix Scripting: Time and Date</title>
		<link>http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/</link>
		<comments>http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 11:30:01 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=55</guid>
		<description><![CDATA[If you have followed this blog for a while, you should remember how to use variables in Unix shell scripts.
Going further, I'd like to show you some basics of working with time and date in your scripts &#8211; generating all sorts of timestamps and timing some parts of your script for reporting purposes.
The history of [...]]]></description>
			<content:encoded><![CDATA[<p>If you have followed this blog for a while, you should remember how to use <a title="variables in Unix scripts" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">variables in Unix shell scripts</a>.</p>
<p>Going further, I'd like to show you some basics of working with time and date in your scripts &#8211; generating all sorts of timestamps and timing some parts of your script for reporting purposes.</p>
<h3>The history of (Unix) time</h3>
<p>In case you didn't know, time in Unix starts with a <strong>Unix epoch</strong>, sometimes also referred to as POSIX epoch.  <em>The Unix epoch</em> is the time <em>00:00:00 UTC on January 1<a>, 1970</a></em><a>.</a></p>
<p>Most of Unix-like system today store and calculate this time according to Unix epoch, which means they all have an internal counter which counts the number of seconds elapsed since midnight of January 1, 1970.</p>
<p>As you can imagine, this is a pretty big number (it passed  1,000,000,000 seconds back in 2001, just so that you know), and reporting in directly would not be very useful to real humans. Because of this, most of Unix time and date reporting commands and functions do the conversion from Unix time into something more meaningful to the end user.</p>
<p>While for the vast majority of time and date related tasks this conversion is good, a task of timing certain events can sometimes benefit from using raw second counters and simply subtracting them when needed.</p>
<h3>Getting Unix time and date</h3>
<p>In Unix shells, the easiest way to get a current time and date is to use the <a title="date command" href="http://www.unixtutorial.org/commands/date/"><strong>date </strong>command</a>:</p>
<pre>ubuntu$ <strong>date</strong>
Tue Jun 10 10:46:07 IST 2008</pre>
<p><a title="date" href="http://www.unixtutorial.org/commands/date/"><strong>date</strong> </a>is a very smart command, and apart from this default behavior it supports template system for printing the current time and date &#8211; so you can use it to report only specific part of the time and date like the current hour or the day of a week or the year.</p>
<p>Read the man page for <strong>date </strong>(type <strong>man date</strong> in your shell prompt) to learn all the details, but this is how you use date output templates:</p>
<pre>ubuntu$ <strong>date "+%b %d, %Y"</strong>
Jun 10, 2008</pre>
<p>In this example, the %b parameter in this template represents the short name of the current month, %d is the day of the month, and %Y is the four-digit representation of the current year.</p>
<h3>Timing parts of your Unix script</h3>
<p>If you're after timing some parts of your script, you'll need to use two variables: one for saving the time before the start of an observed part of the script, and another one for saving the time after the same piece of code.</p>
<p>These two variables will be used to subtract the time and report the elapsed time in seconds, so in order to do this we'll need the date command to report time in seconds. That's why I've given you an introduction to Unix time earlier: date reports the number of seconds since the Unix epoch:</p>
<pre>ubuntu$ <strong>date +%s</strong>
1213091896</pre>
<p>If you run it just a few seconds later, you'll see a different number:</p>
<pre>ubuntu$ <strong>date +%s</strong>
1213091922</pre>
<p>That's why, if such values are saved and then subtracted, we'll get the elapsed time in seconds.</p>
<p>Here's a simple script showing how this is done:</p>
<pre>#!/bin/bash
#
START=`date +%s`
echo "Script start time (Unix epoch): $START"
#
echo "- sleeping for 3 seconds..."
sleep 3
echo "- sleeping for 2 seconds more..."
sleep 2
#
FINISH=`date +%s`
echo "Script finish time (Unix epoch): $START"
#
ELAPSED=`expr $FINISH - $START`
echo "Elapsed time: $ELAPSED"</pre>
<p>And if you run it, you will see this output:</p>
<pre>ubuntu$ <strong>/tmp/time-example.sh</strong>
Script start time (Unix epoch): 1213092131
- sleeping for 3 seconds...
- sleeping for 2 seconds more...
Script finish time (Unix epoch): 1213092131
Elapsed time: 5</pre>
<p>That's all I wanted to show you today. In future posts, I'll show you a few more things you can do regarding timing and timestamps in Unix. Until then &#8211; good luck with your scripting, and feel free to ask if you need any more help!</p>
<h3>Related books</h3>
<p>If you want to learn more, here's a great book:</p>
<div id="attachment_363" class="wp-caption aligncenter" style="width: 137px"><a href="http://www.amazon.com/gp/product/0470183012?ie=UTF8&amp;tag=unixtutorial-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0470183012"><br />
<img class="size-full wp-image-369" title="mastering-unix-shell-scripting" src="http://www.unixtutorial.org/images/mastering-unix-shell-scripting.jpg" alt="mastering-unix-shell-scripting" width="127" height="160" /></a><p class="wp-caption-text">Mastering Unix Shell Scripting</p></div>
<h3>See also:</h3>
<ul>
<li><strong><a title="Unix time" href="http://en.wikipedia.org/wiki/Unix_time">Unix time &#8211; a great article on Wikipedia</a></strong></li>
<li><strong><a title="date command" href="http://www.unixtutorial.org/commands/date/">date command in Unix</a><br />
</strong></li>
<li><strong><a title="Unix shell variables" href="http://www.unixtutorial.org/2008/05/variables-in-unix-shell/">Working with variables in Unix shell</a></strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/06/unix-scripting-time-and-date/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Using variables in Unix shell scripts</title>
		<link>http://www.unixtutorial.org/2008/05/variables-in-unix-shell/</link>
		<comments>http://www.unixtutorial.org/2008/05/variables-in-unix-shell/#comments</comments>
		<pubDate>Wed, 07 May 2008 12:30:58 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Basic stuff]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/?p=48</guid>
		<description><![CDATA[Any Unix shell script longer than a line will most likely involve using variables. Variables are used to store temporary values to simply using them in various Unix commands of your script. The beauty of using variables is that they can be evaluated and set ones, but then reused as many times as you like [...]]]></description>
			<content:encoded><![CDATA[<p>Any Unix shell script longer than a line will most likely involve using variables. Variables are used to store temporary values to simply using them in various Unix commands of your script. The beauty of using variables is that they can be evaluated and set ones, but then reused as many times as you like without your shell interpreter having to re-evaluate them again.</p>
<h3>Defining a variable in Unix shell</h3>
<p>To specify a value for a variable, you need to decide on the variable name &#8211; can be any word or combination of English alphabet symbols and digits, and specify the value.</p>
<p>In Bourne shell (<strong>sh</strong>), Bourne Again Shell (<strong>bash</strong>) and Korn Shell (<strong>ksh</strong>), here's how you would define a new variable and assign it a value:</p>
<pre>CONFIG_FILE="/etc/myfile"</pre>
<p>In C-Shell (<strong>csh</strong>), it's done like this:</p>
<pre>setenv CONFIG_FILE "/etc/myfile"</pre>
<h3>Basic variables usage</h3>
<p>To access the value of a variable, you need to use the same variable name, but with a dollar sign in front of it, like this:</p>
<pre>$CONFIG_FILE</pre>
<p><strong>Important:</strong> to set a new value to the variable, you use just the variable name like CONFIG_FILE, but to access this value later you need to use the $CONFIG_FILE form.</p>
<p>The most basic way to use variables is to assign them constant values at the beginning of your script. This is a good way to define locations of standard files or directories your script will work with, etc:</p>
<pre>#!/bin/sh
#
CONFIG_FILE=/etc/myfile
MY_DIR=/etc
echo $CONFIG_FILE</pre>
<h3>Using output of Unix commands to set variables</h3>
<p>One of the best things about shell scripting is that it's very easy to use any Unix command to generate the output and use it to set the variable.</p>
<p>In this example, I'm running a date command and saving its output as values for my variables:</p>
<pre>ubuntu$ cat /tmp/1.sh</pre>
<pre>#!/bin/sh
#
STARTED=`date`
sleep 5
FINISHED=`date`
#
echo "Script start time: $STARTED"
echo "Script finish time: $FINISHED"</pre>
<p>If I run this simple script, I see the following:</p>
<p>ubuntu$ <strong>/tmp/1.sh</strong><br />
Script start time: Wed May  7 04:56:51 CDT 2008<br />
Script finish time: Wed May  7 04:56:56 CDT 2008<br />
The same approach can be used for practically any scenario.</p>
<p>Here's an example of using uname command to extract some useful information about our system:</p>
<pre>#!/bin/sh
#
STARTED=`date`
NODE=`uname -n`
OS=`uname -o`
CPU=`uname -p`
FINISHED=`date`
#
echo "Nodename: $NODE"
echo "OS type: $OS"
echo "Processor: $CPU"
echo "Script start time: $STARTED"
echo "Script finish time: $FINISHED"</pre>
<p>And this is how it works:</p>
<pre>ubuntu$ <strong>/tmp/1.sh</strong>
Nodename: ubuntu
OS type: GNU/Linux
Processor: unknown
Script start time: Wed May  7 05:05:31 CDT 2008
Script finish time: Wed May  7 05:05:31 CDT 2008</pre>
<p>That's it for today! Let me know what next topic about Unix shell scripting you'd like to see covered, and I'll do my best to explain it in the coming posts.</p>
<h3>Related books</h3>
<p>If you want to learn more, here's a great book:</p>
<div id="attachment_363" class="wp-caption aligncenter" style="width: 137px"><a href="http://www.amazon.com/gp/product/047025128X?ie=UTF8&amp;tag=unixtutorial-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=047025128X"><br />
<img class="size-full wp-image-368" title="linux-command-line-shell-scripting-bible" src="http://www.unixtutorial.org/images/linux-command-line-shell-scripting-bible.jpg" alt="linux-command-line-shell-scripting-bible" width="127" height="160" /></a><p class="wp-caption-text">Linux Command Line Shell Scripting Bible</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2008/05/variables-in-unix-shell/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Perl: Searching Through Directory Trees</title>
		<link>http://www.unixtutorial.org/2007/11/perl-searching-through-directory-trees/</link>
		<comments>http://www.unixtutorial.org/2007/11/perl-searching-through-directory-trees/#comments</comments>
		<pubDate>Thu, 08 Nov 2007 17:17:32 +0000</pubDate>
		<dc:creator>Gleb Reys</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Unix]]></category>

		<guid isPermaLink="false">http://www.unixtutorial.org/unix/perl-searching-through-directory-trees/</guid>
		<description><![CDATA[I had a need to scan a huge directory tree today, identifying the users and Unix groups owning all the files.  The problem I faced was too long usernames and group names which meant the

find /directory -ls
command which I normally use for such tasks wasn't terribly useful because there was no space delimiter between [...]]]></description>
			<content:encoded><![CDATA[<p>I had a need to scan a huge directory tree today, identifying the users and Unix groups owning all the files.  The problem I faced was too long usernames and group names which meant the<strong><br />
</strong></p>
<pre><strong>find /directory -ls</strong></pre>
<p>command which I normally use for such tasks wasn't terribly useful because there was no space delimiter between a username and a group. Results of such scan of the directory tree will have to later be parsed by other tools, and that's why proper splitting of the output into separate fields is so important.</p>
<p align="justify">&nbsp;</p>
<p>This issue was motivational enough to refresh my <a href="http://www.perl.org">Perl</a> skills and sketch the following script (based entirely on this <a href="http://snippets.dzone.com/posts/show/1978">Never Run Unix Find Again</a> article).</p>
<p> It's a very simple piece of code which takes a directory to scan as a parameter.</p>
<h3><strong>How this works</strong></h3>
<p>As you can see,  we're using the standard <em>File:Find</em> functionality, and the two parameters find function takes are the <em>wanted </em>function, where you put conditions for your search.</p>
<p>Within this function, you call lstat to obtain all the necessary information about each directory entry, and then output the necessary fields.</p>
<h3>Perl code</h3>
<pre>#!/usr/bin/perl
use File::Find;
if ($ARGV[0] ne "") {
        $dir = $ARGV[0];
} else {
        print "Please specify a directory!";
        exit;
}

find &amp;wanted, $dir;

sub wanted {
  my $dev;         # the file system device number
  my $ino;         # inode number
  my $mode;        # mode of file
  my $nlink;       # counts number of links to file
  my $uid;         # the ID of the file's owner
  my $gid;         # the group ID of the file's owner
  my $rdev;        # the device identifier
  my $size;        # file size in bytes
  my $atime;       # last access time
  my $mtime;       # last modification time
  my $ctime;       # last change of the mode
  my $blksize;     # block size of file
  my $blocks;      # number of blocks in a file
  my $user;	# username
  my $group;	# unix group name

#Right below here your telling lstat to retrieve all this info on each and every file/directory. Each and every file/directory is written to $_.

  (($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat($_));
  $user = getpwuid($uid);
  $group = getgrgid($gid);

  print $File::Find::name . ":$mode:$size:$user:$group:$ctime:$mtimen";
}</pre>
<p>Hope you find this useful. Good luck with finding all your files! <img src='http://www.unixtutorial.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For further reading, please consult the <a href="http://perldoc.perl.org/File/Find.htm">Perldoc section on File:Find</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.unixtutorial.org/2007/11/perl-searching-through-directory-trees/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
