<?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/"
	xmlns:series="http://unfoldingneurons.com/"
	>

<channel>
	<title>朱文昊 Albert Zhu &#187; 程序设计语言</title>
	<atom:link href="http://zhuwenhao.com/category/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/feed/" rel="self" type="application/rss+xml" />
	<link>http://zhuwenhao.com</link>
	<description>朱文昊的中文博客－－专注技术，向往自由</description>
	<lastBuildDate>Sun, 22 Jan 2012 13:47:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>深入理解C语言</title>
		<link>http://zhuwenhao.com/968/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3c%e8%af%ad%e8%a8%80/</link>
		<comments>http://zhuwenhao.com/968/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3c%e8%af%ad%e8%a8%80/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 13:01:03 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[C 语言]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/?p=968</guid>
		<description><![CDATA[轉載自本站友情鏈接的coolshell，原文鏈接。
朱文昊評註：感謝Ritchie等先驅，他們的聰明才智和貢獻令人欽佩萬分。C語言的很多特性都有歷史的影子，隨著時間的流逝歷史逐漸沈積為基石。這樣，要學好用好C語言，除了可以多瞭解一下計算機科學的發展史，更應該多瞭解一些硬件相關的東西。推薦延伸閱讀資料：《C語言缺陷於陷阱》以及《C語言專家編程》
&#160;
Dennis Ritchie  过世了，他发明了C语言，一个影响深远并彻底改变世界的计算机语言。一门经历40多年的到今天还长盛不衰的语言，今天很多语言都受到C的影响，C++，Java，C#，Perl， PHP， Javascript，  [...]]]></description>
			<content:encoded><![CDATA[<p>轉載自本站友情鏈接的coolshell，<a href="http://coolshell.cn/articles/5761.html" target="_blank">原文鏈接</a>。</p>
<blockquote><p>朱文昊評註：感謝Ritchie等先驅，他們的聰明才智和貢獻令人欽佩萬分。C語言的很多特性都有歷史的影子，隨著時間的流逝歷史逐漸沈積為基石。這樣，要學好用好C語言，除了可以多瞭解一下計算機科學的發展史，更應該多瞭解一些硬件相關的東西。推薦延伸閱讀資料：《C語言缺陷於陷阱》以及《C語言專家編程》</p>
<p>&nbsp;</p></blockquote>
<p>Dennis Ritchie  过世了，他发明了C语言，一个影响深远并彻底改变世界的计算机语言。一门经历40多年的到今天还长盛不衰的语言，今天很多语言都受到C的影响，C++，Java，C#，Perl， PHP， Javascript， 等等。但是，你对C了解吗？相信你看过本站的《<a href="http://coolshell.cn/articles/945.html">C语言的谜题</a>》还有《<a href="http://coolshell.cn/articles/873.html">谁说C语言很简单？</a>》，这里，我再写一篇关于深入理解C语言的文章，一方面是缅怀Dennis，另一方面是告诉大家应该如何学好一门语言。（顺便注明一下，下面的一些例子来源于<a href="http://www.slideshare.net/olvemaudal/deep-c">这个slides</a>）</p>
<p>首先，我们先来看下面这个经典的代码：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code9'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p9689"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p968code9"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">42</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>从这段代码里你看到了什么问题？我们都知道，这段程序里少了一个#include &lt;stdio.h&gt; 还少了一个return 0;的返回语句。</p>
<p>不过，让我们来深入的学习一下，</p>
<ul>
<li>这段代码在C++下无法编译，因为C++需要明确声明函数</li>
<li>这段代码在C的编译器下会编译通过，因为在编译期，编译器会生成一个printf的函数定义，并生成.o文件，链接时，会找到标准的链接库，所以能编译通过。</li>
<li> 但是，你知道这段程序的退出码吗？在ANSI-C下，退出码是一些未定义的垃圾数。但在C89下，退出码是3，因为其取了printf的返回值。为什么printf函数返回3呢？因为其输出了’4′, ’2′,’\n’ 三个字符。而在C99下，其会返回0，也就是成功地运行了这段程序。你可以使用gcc的 -std=c89或是-std=c99来编译上面的程序看结果。</li>
<li>另外，我们还要注意main()，在C标准下，如果一个函数不要参数，应该声明成main(void)，而main()其实相当于main(…)，也就是说其可以有任意多的参数。</li>
</ul>
<p>我们再来看一段代码：</p>
<p>&nbsp;</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code10'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96810"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code" id="p968code10"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span> f<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> b<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> c<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #339933;">++</span>a<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>b<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>c<span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;a=%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;b=%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;c=%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>这个程序会输出什么？</p>
<ul>
<li>我相信你对a的输出相当有把握，就分别是4，5，6，因为那个静态变量。</li>
<li>对于c呢，你应该也比较肯定，那是一堆乱数。</li>
<li>但是你可能不知道b的输出会是什么？答案是1，2，3。为什么和c不一样呢？因为，如果要初始化，每次调用函数里，编译器都要初始化函数栈空间，这太费性能了。但是c的编译器会初始化静态变量为0，因为这只是在启动程序时的动作。</li>
<li>全局变量同样会被初始化。</li>
</ul>
<p>说到全局变量，你知道 静态全局变量和一般全局变量的差别吗？是的，对于static 的全局变量，其对链接器不可以见，也就是说，这个变量只能在当前文件中使用。</p>
<p>我们再来看一个例子：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code11'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96811"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code" id="p968code11"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span> foo<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> bar<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">42</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
bar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
foo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>你知道这段代码会输出什么吗？A) 一个随机值，B) 42。A 和 B都对（在“<a href="http://coolshell.cn/articles/4907.html">在函数外存取局部变量的一个比喻</a>”文中的最后给过这个例子），不过，你知道为什么吗？</p>
<ul>
<li>如果你使用一般的编译，会输出42，因为我们的编译器优化了函数的调用栈（重用了之前的栈），为的是更快，这没有什么副作用。反正你不初始化，他就是随机值，既然是随机值，什么都无所谓。</li>
<li>但是，如果你的编译打开了代码优化的开关，-O，这意味着，foo()函数的代码会被优化成main()里的一个inline函数，也就是说没有函数调用，就像宏定义一样。于是你会看到一个随机的垃圾数。</li>
</ul>
<p>下面，我们再来看一个示例：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code12'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96812"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p968code12"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> b<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #0000dd;">3</span>”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> c<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #0000dd;">4</span>”<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> b<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> c<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>这段程序会输出什么？，你会说是，3，4，7。但是我想告诉你，这也有可能输出，4，3，7。为什么呢？ 这是因为，在C/C++中，表达的评估次序是没有标准定义的。编译器可以正着来，也可以反着来，所以，不同的编译器会有不同的输出。你知道这个特性以后，你就知道这样的程序是没有可移植性的。</p>
<p>我们再来看看下面的这堆代码，他们分别输出什么呢？</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code13'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96813"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p968code13"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> a<span style="color: #339933;">=</span><span style="color: #0000dd;">41</span><span style="color: #339933;">;</span> a<span style="color: #339933;">++;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">=</span><span style="color: #0000dd;">41</span><span style="color: #339933;">;</span> a<span style="color: #339933;">++</span> <span style="color: #339933;">&amp;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">=</span><span style="color: #0000dd;">41</span><span style="color: #339933;">;</span> a<span style="color: #339933;">++</span> <span style="color: #339933;">&amp;&amp;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">=</span><span style="color: #0000dd;">41</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>a<span style="color: #339933;">++</span> <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">42</span><span style="color: #009900;">&#41;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">=</span><span style="color: #0000dd;">41</span><span style="color: #339933;">;</span> a <span style="color: #339933;">=</span> a<span style="color: #339933;">++;</span> <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span>“<span style="color: #339933;">%</span>d\n”<span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>只有示例一，示例三，示例四输出42，而示例二和五的行为则是未定义的。关于这种未定义的东西是因为Sequence Points的影响（Sequence Points是一种规则，也就是程序执行的序列点，在两点之间的表达式只能对变量有一次修改），因为这会让编译器不知道在一个表达式顺列上如何存取变量的值。比如a = a++，a + a++，不过，在C中，这样的情况很少。</p>
<p>下面，再看一段代码：（假设int为4字节，char为1字节）</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code14'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96814"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p968code14"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span> X <span style="color: #009900;">&#123;</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">;</span> <span style="color: #993333;">char</span> b<span style="color: #339933;">;</span> <span style="color: #993333;">int</span> c<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d,&quot;</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> X<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">struct</span> Y <span style="color: #009900;">&#123;</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">;</span> <span style="color: #993333;">char</span> b<span style="color: #339933;">;</span> <span style="color: #993333;">int</span> c<span style="color: #339933;">;</span> <span style="color: #993333;">char</span> d<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> Y<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>这个代码会输出什么?</p>
<p>a) 9，10<br />
b)12, 12<br />
c)12, 16</p>
<p>答案是C，我想，你一定知道字节对齐，是向4的倍数对齐。</p>
<ul>
<li>但是，你知道为什么要字节对齐吗？还是因为性能。因为这些东西都在内存里，如果不对齐的话，我们的编译器就要向内存一个字节一个字节的取，这样一来，struct X，就需要取9次，太浪费性能了，而如果我一次取4个字节，那么我三次就搞定了。所以，这是为了性能的原因。</li>
<li>但是，为什么struct Y不向12 对齐，却要向16对齐，因为char d; 被加在了最后，当编译器计算一个结构体的尺寸时，是边计算，边对齐的。也就是说，编译器先看到了int，很好，4字节，然后是 char，一个字节，而后面的int又不能填上还剩的3个字节，不爽，把char b对齐成4，于是计算到d时，就是13 个字节，于是就是16啦。但是如果换一下d和c的声明位置，就是12了。</li>
</ul>
<p>另外，再提一下，上述程序的printf中的%d并不好，因为，在64位下，sizeof的size_t是unsigned long，而32位下是 unsigned int，所以，C99引入了一个专门给size_t用的%zu。这点需要注意。在64位平台下，C/C++ 的编译需要注意很多事。你可以参看《<a href="http://coolshell.cn/articles/3512.html">64位平台C/C++开发注意事项</a>》。</p>
<p>下面，我们再说说编译器的Warning，请看代码：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code15'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96815"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p968code15"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>考虑下面两种编译代码的方式 ：</p>
<ul>
<li>cc -Wall a.c</li>
<li>cc -Wall -O a.c</li>
</ul>
<p>前一种是不会编译出a未初化的警告信息的，而只有在-O的情况下，才会有未初始化的警告信息。这点就是为什么我们在makefile里的CFLAGS上总是需要-Wall和 -O。</p>
<p>最后，我们再来看一个指针问题，你看下面的代码：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p968code16'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p96816"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code" id="p968code16"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> a<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">5</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%x<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%x<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%x<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span>a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%x<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span>a<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>假如我们的a的地址是：0Xbfe2e100, 而且是32位机，那么这个程序会输出什么？</p>
<ul>
<li>第一条printf语句应该没有问题，就是 bfe2e100</li>
<li>第二条printf语句你可能会以为是bfe2e101。那就错了，a+1，编译器会编译成 a+ 1*sizeof(int)，int在32位下是4字节，所以是加4，也就是bfe2e104</li>
<li>第三条printf语句可能是你最头疼的，我们怎么知道a的地址？我不知道吗？可不就是bfe2e100。那岂不成了a==&amp;a啦？这怎么可能？自己存自己的？也许很多人会觉得指针和数组是一回事，那么你就错了。如果是 int *a，那么没有问题，因为a是指针，所以 &amp;a 是指针的地址，a 和 &amp;a不一样。但是这是数组啊a[]，所以&amp;a其实是被编译成了 &amp;a[0]。</li>
<li>第四条printf语句就很自然了，就是bfe2e104。还是不对，因为是&amp;a是数组，被看成int(*)[5]，所以sizeof(a)是5，也就是5*sizeof(int)，也就是bfe2e114。</li>
</ul>
<p>看过这么多，你可能会觉得C语言设计得真扯淡啊。不过我要告诉下面几点Dennis当初设计C语言的初衷：</p>
<p><strong>1）相信程序员，不阻止程序员做他们想做的事。</strong></p>
<p><strong>2）保持语言的简洁，以及概念上的简单。</strong></p>
<p><strong>3）保证性能，就算牺牲移植性。</strong></p>
<p>今天很多语言进化得很高级了，语法也越来越复杂和强大，但是C语言依然光芒四射，Dennis离世了，但是C语言的这些设计思路将永远不朽。</p>
<p><strong>（请勿用于商业用途，转载时请注明作者和出处）</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/968/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3c%e8%af%ad%e8%a8%80/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>gcc扩展，在Linux Kernel中的使用示例</title>
		<link>http://zhuwenhao.com/387/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/gcc%e6%89%a9%e5%b1%95%ef%bc%8c%e5%9c%a8linux-kernel%e4%b8%ad%e7%9a%84%e4%bd%bf%e7%94%a8%e7%a4%ba%e4%be%8b/</link>
		<comments>http://zhuwenhao.com/387/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/gcc%e6%89%a9%e5%b1%95%ef%bc%8c%e5%9c%a8linux-kernel%e4%b8%ad%e7%9a%84%e4%bd%bf%e7%94%a8%e7%a4%ba%e4%be%8b/#comments</comments>
		<pubDate>Thu, 13 May 2010 07:10:34 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[C 语言]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/?p=387</guid>
		<description><![CDATA[GNC CC 是一个功能非常强大的跨平台 C 编译器，它对 C 语言提供了很多扩展，这些扩展对优化、目标代码布局、更安全的检查等方面提供了很强的支持。本文把支持 GNU 扩展的 C 语言称为 GNU C。 Linux 内核代码使用了大量的 GNU C 扩展，以至于能够编译 Linux 内核的唯一编译器是 GNU CC，以前甚至出现过编译 Linux 内核要使用特殊的 GNU CC 版本的情
况。本文是对 Linux 内核使用的 GNU C 扩展的一个汇总，希望当你读内核源码遇到不理解的语法和语义时，能从本文找到一个初步的解答，更详细的信息可以查看gcc.info。文中的例子取自 Linux  [...]]]></description>
			<content:encoded><![CDATA[<p>GNC CC 是一个功能非常强大的跨平台 C 编译器，它对 C 语言提供了很多扩展，这些扩展对优化、目标代码布局、更安全的检查等方面提供了很强的支持。本文把支持 GNU 扩展的 C 语言称为 GNU C。 Linux 内核代码使用了大量的 GNU C 扩展，以至于能够编译 Linux 内核的唯一编译器是 GNU CC，以前甚至出现过编译 Linux 内核要使用特殊的 GNU CC 版本的情<br />
况。本文是对 Linux 内核使用的 GNU C 扩展的一个汇总，希望当你读内核源码遇到不理解的语法和语义时，能从本文找到一个初步的解答，更详细的信息可以查看gcc.info。文中的例子取自 Linux 2.4.18。</p>
<p>语句表达式<br />
==========<br />
GNU C 把包含在括号中的复合语句看做是一个表达式，称为语句表达式，它可以出现在任何允许表达式的地方，你可以在语句表达式中使用循环、局部变量等，原本只能在复合语句中使用。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code37'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38737"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p387code37"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>kernel.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">159</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define min_t(type,x,y) \
160: ({ type __x = (x); type __y = (y); __x &amp;lt; __y ? __x: __y; })</span>
<span style="color: #339933;">++++</span> net<span style="color: #339933;">/</span>ipv4<span style="color: #339933;">/</span>tcp_output.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">654</span><span style="color: #339933;">:</span> <span style="color: #993333;">int</span> full_space <span style="color: #339933;">=</span> min_t<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #339933;">,</span> tp<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>window_clamp<span style="color: #339933;">,</span> tcp_full_space<span style="color: #009900;">&#40;</span>sk<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>复合语句的最后一个语句应该是一个表达式，它的值将成为这个语句表达式的值。这里定义了一个安全的求最小值的宏，在标准 C 中，通常定义为:</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code38'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38738"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code38"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#define min(x,y) ((x) &amp;lt; (y) ? (x) : (y))</span></pre></td></tr></table></div>

<p>这个定义计算 x 和 y 分别两次，当参数有副作用时，将产生不正确的结果，使用语句表达式只计算参数一次，避免了可能的错误。语句表达式通常用于宏定义。</p>
<p>Typeof<br />
======<br />
使用前一节定义的宏需要知道参数的类型，利用 typeof 可以定义更通用的宏，不必事先知道参数的类型，例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code39'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38739"><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" id="p387code39"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>kernel.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">141</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define min(x,y) ({ \
142: const typeof(x) _x = (x); \
143: const typeof(y) _y = (y); \
144: (void) (&amp;amp;_x == &amp;amp;_y); \
145: _x &amp;lt; _y ? _x : _y; })</span></pre></td></tr></table></div>

<p>这里 typeof(x) 表示 x 的值类型，第 142 行定义了一个与 x 类型相同的局部变量 _x 并初使化为 x，注意第 144 行的作用是检查参数 x 和 y 的类型是否相同。typeof 可以用在任何类型可以使用的地方，通常用于宏定义。<br />
零长度数组<br />
======<br />
GNU C 允许使用零长度数组，在定义变长对象的头结构时，这个特性非常有用。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code40'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38740"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p387code40"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>minix_fs.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">85</span><span style="color: #339933;">:</span> <span style="color: #993333;">struct</span> minix_dir_entry <span style="color: #009900;">&#123;</span>
<span style="color: #0000dd;">86</span><span style="color: #339933;">:</span> __u16 inode<span style="color: #339933;">;</span>
<span style="color: #0000dd;">87</span><span style="color: #339933;">:</span> <span style="color: #993333;">char</span> name<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">88</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>结构的最后一个元素定义为零长度数组，它不占结构的空间。在标准 C 中则需要定义数组长度为 1，分配时计算对象大小比较复杂。<br />
可变参数宏<br />
==========<br />
在 GNU C 中，宏可以接受可变数目的参数，就象函数一样，例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code41'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38741"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p387code41"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>kernel.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">110</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define pr_debug(fmt,arg...) \
111: printk(KERN_DEBUG fmt,##arg)</span></pre></td></tr></table></div>

<p>这里 arg 表示其余的参数，可以是零个或多个，这些参数以及参数之间的逗号构成 arg 的值，在宏扩展时替换 arg，例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code42'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38742"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code42"><pre class="c" style="font-family:monospace;">pr_debug<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s:%d&quot;</span><span style="color: #339933;">,</span>filename<span style="color: #339933;">,</span>line<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>扩展为</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code43'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38743"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code43"><pre class="c" style="font-family:monospace;">printk<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;&lt;7&gt;&quot;</span>  <span style="color: #ff0000;">&quot;%s:%d&quot;</span><span style="color: #339933;">,</span> filename<span style="color: #339933;">,</span> line<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>使用 ## 的原因是处理 arg 不匹配任何参数的情况，这时 arg 的值为空，GNU C 预处理器在这种特殊情况下，丢弃 ## 之前的逗号，这样</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code44'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38744"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code44"><pre class="c" style="font-family:monospace;">pr_debug<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;success!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>扩展为</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code45'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38745"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code45"><pre class="c" style="font-family:monospace;">printk<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;&lt;7&gt;&quot;</span>  <span style="color: #ff0000;">&quot;success!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>注意最后没有逗号。<br />
标号元素<br />
========<br />
标准 C 要求数组或结构变量的初使化值必须以固定的顺序出现，在 GNU C 中，通过指定索引或结构域名，允许初始化值以任意顺序出现。指定数组索引的方法是在初始化值前写 &#8216;[INDEX] =&#8217;，要指定一个范围使用[FIRST ... LAST] =&#8217; 的形式，<br />
例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code46'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38746"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p387code46"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">+++++</span> arch<span style="color: #339933;">/</span>i386<span style="color: #339933;">/</span>kernel<span style="color: #339933;">/</span>irq.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">1079</span><span style="color: #339933;">:</span> <span style="color: #993333;">static</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> irq_affinity <span style="color: #009900;">&#91;</span>NR_IRQS<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span> ... <span style="color: #202020;">NR_IRQS</span><span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> ~0UL <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>将数组的所有元素初使化为 ~0UL，这可以看做是一种简写形式。<br />
要指定结构元素，在元素值前写 &#8216;FIELDNAME:&#8217;，例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code47'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38747"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p387code47"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> fs<span style="color: #339933;">/</span>ext2<span style="color: #339933;">/</span>file.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">41</span><span style="color: #339933;">:</span> <span style="color: #993333;">struct</span> file_operations ext2_file_operations <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
<span style="color: #0000dd;">42</span><span style="color: #339933;">:</span> llseek<span style="color: #339933;">:</span> generic_file_llseek<span style="color: #339933;">,</span>
<span style="color: #0000dd;">43</span><span style="color: #339933;">:</span> read<span style="color: #339933;">:</span> generic_file_read<span style="color: #339933;">,</span>
<span style="color: #0000dd;">44</span><span style="color: #339933;">:</span> write<span style="color: #339933;">:</span> generic_file_write<span style="color: #339933;">,</span>
<span style="color: #0000dd;">45</span><span style="color: #339933;">:</span> ioctl<span style="color: #339933;">:</span> ext2_ioctl<span style="color: #339933;">,</span>
<span style="color: #0000dd;">46</span><span style="color: #339933;">:</span> mmap<span style="color: #339933;">:</span> generic_file_mmap<span style="color: #339933;">,</span>
<span style="color: #0000dd;">47</span><span style="color: #339933;">:</span> open<span style="color: #339933;">:</span> generic_file_open<span style="color: #339933;">,</span>
<span style="color: #0000dd;">48</span><span style="color: #339933;">:</span> release<span style="color: #339933;">:</span> ext2_release_file<span style="color: #339933;">,</span>
<span style="color: #0000dd;">49</span><span style="color: #339933;">:</span> fsync<span style="color: #339933;">:</span> ext2_sync_file<span style="color: #339933;">,</span>
<span style="color: #0000dd;">50</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>将结构 ext2_file_operations 的元素 llseek 初始化为 generic_file_llseek，元素 read 初始化为 genenric_file_read，依次类推。我觉得这是 GNU C 扩展中最好的特性之一，当结构的定义变化以至元素的偏移改变时，这种初始化方法仍然保证已知元素的正确性。对于未出现在初始化中的元素，其初值为 0。<br />
Case 范围<br />
=========<br />
GNU C 允许在一个 case 标号中指定一个连续范围的值，例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code48'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38748"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p387code48"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> arch<span style="color: #339933;">/</span>i386<span style="color: #339933;">/</span>kernel<span style="color: #339933;">/</span>irq.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">1062</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'0'</span> ... <span style="color: #ff0000;">'9'</span><span style="color: #339933;">:</span> c <span style="color: #339933;">-=</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">1063</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'a'</span> ... <span style="color: #ff0000;">'f'</span><span style="color: #339933;">:</span> c <span style="color: #339933;">-=</span> <span style="color: #ff0000;">'a'</span><span style="color: #339933;">-</span><span style="color: #0000dd;">10</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">1064</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'A'</span> ... <span style="color: #ff0000;">'F'</span><span style="color: #339933;">:</span> c <span style="color: #339933;">-=</span> <span style="color: #ff0000;">'A'</span><span style="color: #339933;">-</span><span style="color: #0000dd;">10</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'0'</span> ... <span style="color: #ff0000;">'9'</span><span style="color: #339933;">:</span></pre></td></tr></table></div>

<p>相当于</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code49'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38749"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p387code49"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'0'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'1'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'2'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'3'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'4'</span><span style="color: #339933;">:</span>
<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'5'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'6'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'7'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'8'</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'9'</span><span style="color: #339933;">:</span></pre></td></tr></table></div>

<p>声明的特殊属性<br />
==============<br />
GNU C 允许声明函数、变量和类型的特殊属性，以便手工的代码优化和更仔细的代码检查。要指定一个声明的属性，在声明后写</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code50'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38750"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p387code50"><pre class="c" style="font-family:monospace;">__attribute__ <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span> ATTRIBUTE <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>其中 ATTRIBUTE 是属性说明，多个属性以逗号分隔。GNU C 支持十几个属性，这里介绍最常用的：<br />
* noreturn<br />
属性 noreturn 用于函数，表示该函数从不返回。这可以让编译器生成稍微优化的代码，最重要的是可以消除不必要的警告信息比如未初使化的变量。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code51'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38751"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p387code51"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>kernel.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">47</span><span style="color: #339933;">:</span> <span style="color: #339933;"># define ATTRIB_NORET __attribute__((noreturn)) ....</span>
<span style="color: #0000dd;">61</span><span style="color: #339933;">:</span> asmlinkage NORET_TYPE <span style="color: #993333;">void</span> do_exit<span style="color: #009900;">&#40;</span><span style="color: #993333;">long</span> error_code<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>ATTRIB_NORET;<br />
* format (ARCHETYPE, STRING-INDEX, FIRST-TO-CHECK)<br />
属性 format 用于函数，表示该函数使用 printf, scanf 或 strftime 风格的参数，使用这类函数最容易犯的错误是格式串与参数不匹配，指定 format 属性可以让编译器根据格式串检查参数类型。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code52'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38752"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p387code52"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>kernel.<span style="color: #202020;">h</span><span style="color: #339933;">?</span>
<span style="color: #0000dd;">89</span><span style="color: #339933;">:</span> asmlinkage <span style="color: #993333;">int</span> printk<span style="color: #009900;">&#40;</span><span style="color: #993333;">const</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span> fmt<span style="color: #339933;">,</span> ...<span style="color: #009900;">&#41;</span>
<span style="color: #0000dd;">90</span><span style="color: #339933;">:</span> __attribute__ <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>format <span style="color: #009900;">&#40;</span><a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>表示第一个参数是格式串，从第二个参数起根据格式串检查参数。<br />
* unused<br />
属性 unused 用于函数和变量，表示该函数或变量可能不使用，这个属性可以避免编译器产生警告信息。<br />
* section (“section-name”)<br />
属性 section 用于函数和变量，通常编译器将函数放在 .text 节，变量放在.data 或 .bss 节，使用 section 属性，可以让编译器将函数或变量放在指定的节中。</p>
<p>GNU CC 预定义了两个标志符保存当前函数的名字，__FUNCTION__ 保存函数在源码中的名字，__PRETTY_FUNCTION__ 保存带语言特色的名字。在 C 函数中，这两个名字是相同的，在 C++ 函数中，__PRETTY_FUNCTION__ 包括函数返回类型等额外信息，Linux 内核只使用了 __FUNCTION__。</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code53'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38753"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p387code53"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> fs<span style="color: #339933;">/</span>ext2<span style="color: #339933;">/</span>super.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">98</span><span style="color: #339933;">:</span> <span style="color: #993333;">void</span> ext2_update_dynamic_rev<span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> super_block <span style="color: #339933;">*</span>sb<span style="color: #009900;">&#41;</span>
<span style="color: #0000dd;">99</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
<span style="color: #0000dd;">100</span><span style="color: #339933;">:</span> <span style="color: #993333;">struct</span> ext2_super_block <span style="color: #339933;">*</span>es <span style="color: #339933;">=</span> EXT2_SB<span style="color: #009900;">&#40;</span>sb<span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>s_es<span style="color: #339933;">;</span>
<span style="color: #0000dd;">101</span><span style="color: #339933;">:</span>
<span style="color: #0000dd;">102</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>le32_to_cpu<span style="color: #009900;">&#40;</span>es<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>s_rev_level<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> EXT2_GOOD_OLD_REV<span style="color: #009900;">&#41;</span>
<span style="color: #0000dd;">103</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">104</span><span style="color: #339933;">:</span>
<span style="color: #0000dd;">105</span><span style="color: #339933;">:</span> ext2_warning<span style="color: #009900;">&#40;</span>sb<span style="color: #339933;">,</span> __FUNCTION__<span style="color: #339933;">,</span>
<span style="color: #0000dd;">106</span><span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;updating to rev %d because of new feature flag, &quot;</span>
<span style="color: #0000dd;">107</span><span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;running e2fsck is recommended&quot;</span><span style="color: #339933;">,</span>
<span style="color: #0000dd;">108</span><span style="color: #339933;">:</span> EXT2_DYNAMIC_REV<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>这里 __FUNCTION__ 将被替换为字符串 “ext2_update_dynamic_rev”。虽然__FUNCTION__ 看起来类似于标准 C 中的 __FILE__，但实际上 __FUNCTION__是被编译器替换的，不象 __FILE__ 被预处理器替换。<br />
内建函数<br />
========<br />
GNU C 提供了大量的内建函数，其中很多是标准 C 库函数的内建版本，例如memcpy，它们与对应的 C 库函数功能相同，本文不讨论这类函数，其他内建函数的名字通常以 __builtin 开始。<br />
* __builtin_return_address (LEVEL)<br />
内建函数 __builtin_return_address 返回当前函数或其调用者的返回地址，参数LEVEL 指定在栈上搜索框架的个数，0 表示当前函数的返回地址，1 表示当前函数的调用者的返回地址，依此类推。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code54'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38754"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p387code54"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> kernel<span style="color: #339933;">/</span>sched.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">437</span><span style="color: #339933;">:</span> printk<span style="color: #009900;">&#40;</span>KERN_ERR <span style="color: #ff0000;">&quot;schedule_timeout: wrong timeout &quot;</span>
<span style="color: #0000dd;">438</span><span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;value %lx from %p<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> timeout<span style="color: #339933;">,</span>
<span style="color: #0000dd;">439</span><span style="color: #339933;">:</span> __builtin_return_address<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>* __builtin_constant_p(EXP)<br />
内建函数 __builtin_constant_p 用于判断一个值是否为编译时常数，如果参数EXP 的值是常数，函数返回 1，否则返回 0。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code55'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38755"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p387code55"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>asm<span style="color: #339933;">-</span>i386<span style="color: #339933;">/</span>bitops.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">249</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define test_bit(nr,addr) \
250: (__builtin_constant_p(nr) ? \
251: constant_test_bit((nr),(addr)) : \
252: variable_test_bit((nr),(addr)))</span></pre></td></tr></table></div>

<p>很多计算或操作在参数为常数时有更优化的实现，在 GNU C 中用上面的方法可以根据参数是否为常数，只编译常数版本或非常数版本，这样既不失通用性，又能在参数是常数时编译出最优化的代码。<br />
* __builtin_expect(EXP, C)<br />
内建函数 __builtin_expect 用于为编译器提供分支预测信息，其返回值是整数表达式 EXP 的值，C 的值必须是编译时常数。例如：</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p387code56'); return false;">View Code</a> C</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p38756"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p387code56"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">++++</span> include<span style="color: #339933;">/</span>linux<span style="color: #339933;">/</span>compiler.<span style="color: #202020;">h</span>
<span style="color: #0000dd;">13</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define likely(x) __builtin_expect((x),1)</span>
<span style="color: #0000dd;">14</span><span style="color: #339933;">:</span> <span style="color: #339933;">#define unlikely(x) __builtin_expect((x),0)</span>
<span style="color: #339933;">++++</span> kernel<span style="color: #339933;">/</span>sched.<span style="color: #202020;">c</span>
<span style="color: #0000dd;">564</span><span style="color: #339933;">:</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>unlikely<span style="color: #009900;">&#40;</span>in_interrupt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #0000dd;">565</span><span style="color: #339933;">:</span> printk<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Scheduling in interrupt<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">566</span><span style="color: #339933;">:</span> BUG<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #0000dd;">567</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>这个内建函数的语义是 EXP 的预期值是 C，编译器可以根据这个信息适当地重排语句块的顺序，使程序在预期的情况下有更高的执行效率。上面的例子表示处于中断上下文是很少发生的，第 565-566 行的目标码可能会放在较远的位置，以保证经常执行的目标码更紧凑。 ﻿</p>
]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/387/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/gcc%e6%89%a9%e5%b1%95%ef%bc%8c%e5%9c%a8linux-kernel%e4%b8%ad%e7%9a%84%e4%bd%bf%e7%94%a8%e7%a4%ba%e4%be%8b/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>程序员修炼之路－C语言</title>
		<link>http://zhuwenhao.com/375/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e7%a8%8b%e5%ba%8f%e5%91%98%e4%bf%ae%e7%82%bc%e4%b9%8b%e8%b7%af%ef%bc%8dc%e8%af%ad%e8%a8%80/</link>
		<comments>http://zhuwenhao.com/375/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e7%a8%8b%e5%ba%8f%e5%91%98%e4%bf%ae%e7%82%bc%e4%b9%8b%e8%b7%af%ef%bc%8dc%e8%af%ad%e8%a8%80/#comments</comments>
		<pubDate>Sun, 09 May 2010 12:50:59 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[C 语言]]></category>
		<category><![CDATA[构造]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/?p=375</guid>
		<description><![CDATA[在程序员修炼之路这个系列里面，转载过几篇他人的文章。最近有同学问我如何深入学习C语言和职业规划的问题，让我决心自己动手总结一些观点，和朋友共勉。于是就有了这篇同名文章。
要想成为一名合格的C语言程序员，读什么样的书是一个首先碰到的基本问题。我的品位是，读计算机方面的著作，一定要读国外人写的经典级别的书。回忆我的往事，在中学时候看了一点BASIC基础，学会了盲打，会用了Windows  [...]]]></description>
			<content:encoded><![CDATA[<p>在程序员修炼之路这个系列里面，转载过几篇他人的文章。最近有同学问我如何深入学习C语言和职业规划的问题，让我决心自己动手总结一些观点，和朋友共勉。于是就有了这篇同名文章。</p>
<p>要想成为一名合格的C语言程序员，读什么样的书是一个首先碰到的基本问题。我的品位是，读计算机方面的著作，一定要读国外人写的经典级别的书。回忆我的往事，在中学时候看了一点BASIC基础，学会了盲打，会用了Windows 3X和95，这些就是我在读大学前全部的计算机基础知识。在大学第一年的寒假，回家的火车上，我没有买到座位票，于是只好站着回家。在这十八个小时的旅途中，我阅读了大约1/2的《C程序设计语言》，对，就是那本Kernighan和Richie合著的薄薄的书。不过惭愧的是，我当时的英语很差，读的当然是东南大学徐宝文翻译的第一版。徐先生的翻译很好，所以我才能顺利读下来。有人可能觉得奇怪，没有什么基础的情况下，如何能读完这么一本书？我的感受是，当要学习一种全新的东西，读书不能奢望全理解，勇敢的看下去，看完它，和作者的第一次沟通才能完成。</p>
<p>这第一次沟通，奠定了我的C语言基础知识，也决定了我今后在C语言程序员、系统软件设计、嵌入式系统设计等方面的职业脉络。读了第一本C语言经典之后，应该就可以编写一些和书中例程差不多的小程序了。接下来需要阅读的经典有：《C专家编程》(Expert C Programming &#8212; Deep C Secrets)、《C陷阱与缺陷》(C Traps and Pitfalls)、《C和指针》(Pointers on C)、《C语言核心技术》(C in a Nutshell)、《代码大全》(Code Complete)。读完了这些书，基本上就可以号称是C语言程序员了。</p>
<p>其中《C和指针》我接触的比较晚，非常的遗憾。当我读了《C和指针》，那种相见恨晚的感觉，难于言表。《C专家编程》《C陷阱与缺陷》这两本书，作者处的时代很久远了。如果在现代PC程序设计领域，相关问题可能很少遇到。但是对C语言程序员而言，还是要继续列为必读书目，因为那些晦涩的问题，还是会不停的重现在嵌入式系统的硬件和编译环境里。《代码大全》结合一定的工作经验来读，会有更深的感触。</p>
<p>学习C语言的路还没有结束，真的要理解C语言，你就要了解“语言”，读一读《程学设计语言》(Programming Language-Michael L. Scott)吧。这本研究生和本科课程通用的教材，会让你对C语言的了解上升一个层次，不，一个数量级。</p>
<p>过了这个界线，C语言的学习就该依据职业规划来细分道路了。我只能根据自己的经验谈谈。</p>
<p>首先，学会用Linux操作体系或者其他类似的＊nix系统，因为这些系统是面向程序员的操作系统，如果你真的是一个程序员，在＊nix你会感到更舒服。会用Gcc也是必须的。</p>
<p>其次，读一下Intel出版的《多核程序设计》。</p>
<p>(本文未完成，请期待更新)</p>
]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/375/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/c-%e8%af%ad%e8%a8%80/%e7%a8%8b%e5%ba%8f%e5%91%98%e4%bf%ae%e7%82%bc%e4%b9%8b%e8%b7%af%ef%bc%8dc%e8%af%ad%e8%a8%80/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[程序员修炼之路]]></series:name>
	</item>
		<item>
		<title>Bash scripting Tutorial</title>
		<link>http://zhuwenhao.com/339/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/bash/bash-scripting-tutorial/</link>
		<comments>http://zhuwenhao.com/339/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/bash/bash-scripting-tutorial/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 09:31:59 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[Bash]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/339/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/bash/bash-scripting-tutorial/</guid>
		<description><![CDATA[This bash script tutorial assumes no previous knowledge of bash scripting.As you will soon discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is very easy task. Lets begin this bash scripting tutorial with a simple &#34;Hello World&#34; script. Let&#8217;s start with  [...]]]></description>
			<content:encoded><![CDATA[<p>This bash script tutorial assumes no previous knowledge of bash scripting.As you will soon discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is very easy task. Lets begin this bash scripting tutorial with a simple &quot;Hello World&quot; script. Let&#8217;s start with Learning the bash Shell: Unix Shell Programming </p>
<h3>1. Hello World Bash Shell Script</h3>
<p>First you need to find out where is your bash interpreter located. Enter the following into your command line: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code105'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339105"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code105"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">which</span> <span style="color: #c20cb9; font-weight: bold;">bash</span></pre></td></tr></table></div>

<p><img title="Locate a Bash Interpreter" border="0" alt="bash interpreter &#13;&#10;location: /bin/bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/c9eeef568dc6a74c06196739cdd71f00.gif" width="188" height="43" /></p>
<p>Open up you favorite text editor and a create file called hello_world.sh. Insert the following lines to a file: </p>
<p>NOTE:Every bash shell script in this tutorial starts with <b>shebang:&quot;#!&quot;</b> which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash. </p>
<p>Here is our first bash shell script example: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code106'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339106"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p339code106"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># declare STRING variable</span>
<span style="color: #007800;">STRING</span>=<span style="color: #ff0000;">&quot;Hello World&quot;</span>
<span style="color: #666666; font-style: italic;">#print variable on a screen</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$STRING</span></pre></td></tr></table></div>

<p>Navigate to a directory where your hello_world.sh is located and make the file executable: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code107'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339107"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code107"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">chmod</span> +x hello_world.sh</pre></td></tr></table></div>

<p><img title="Make bash shell script executable" border="0" alt="Make bash shell &#13;&#10;script executable" src="http://zhuwenhao.com/wp-content/uploads/HLIC/0a2c82757f4f905a489385556026db66.gif" width="263" height="30" /></p>
<p>Now you are ready to execute your first bash script: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code108'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339108"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code108"><pre class="bash" style="font-family:monospace;">.<span style="color: #000000; font-weight: bold;">/</span>hello_world.sh</pre></td></tr></table></div>

<p><img title="Example of simple bash shell script" border="0" alt="Example of simple bash shell &#13;&#10;script" src="http://zhuwenhao.com/wp-content/uploads/HLIC/7ff02785e875790a94eb50726f4a8622.gif" width="214" height="43" /></p>
<h3>2. Simple Backup bash shell script</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code109'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339109"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p339code109"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-czf</span> myhome_directory.tar.gz <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>linuxconfig</pre></td></tr></table></div>

<p><img title="Simple Backup bash script" border="0" alt="Simple &#13;&#10;Backup bash script" src="http://zhuwenhao.com/wp-content/uploads/HLIC/b477d46aadf122af534ad4d83fbc22b8.gif" /></p>
<h3>3. Variables</h3>
<p>In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code110'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339110"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p339code110"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
 <span style="color: #007800;">STRING</span>=<span style="color: #ff0000;">&quot;HELLO WORLD!!!&quot;</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$STRING</span></pre></td></tr></table></div>

<p><img title="Bash string Variables in bash &#13;&#10;script" border="0" alt="Bash &#13;&#10;string Variables in bash script" src="http://zhuwenhao.com/wp-content/uploads/HLIC/ae5462d925fe223bf74b9d6a8bd084da.gif" width="484" height="43" /></p>
<p>Your backup script and variables: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code111'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339111"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p339code111"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
 <span style="color: #007800;">OF</span>=myhome_directory_$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #c20cb9; font-weight: bold;">date</span> +<span style="color: #000000; font-weight: bold;">%</span>Y<span style="color: #000000; font-weight: bold;">%</span>m<span style="color: #000000; font-weight: bold;">%</span>d<span style="color: #7a0874; font-weight: bold;">&#41;</span>.tar.gz
 <span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-czf</span> <span style="color: #007800;">$OF</span> <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>linuxconfig</pre></td></tr></table></div>

<p><img title="Bash backup Script with bash &#13;&#10;Variables" border="0" alt="Bash &#13;&#10;backup Script with bash Variables" src="http://zhuwenhao.com/wp-content/uploads/HLIC/0492f1b253e3206e74a27d801ab6df8e.gif" width="484" height="69" /></p>
<h4>3.1. Global vs. Local variables</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code112'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339112"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p339code112"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Define bash global variable</span>
<span style="color: #666666; font-style: italic;">#This variable is global and can be used anywhere in this bash script</span>
<span style="color: #007800;">VAR</span>=<span style="color: #ff0000;">&quot;global variable&quot;</span>
<span style="color: #000000; font-weight: bold;">function</span> <span style="color: #c20cb9; font-weight: bold;">bash</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
<span style="color: #666666; font-style: italic;">#Define bash local variable</span>
<span style="color: #666666; font-style: italic;">#This variable is local to bash function only</span>
<span style="color: #7a0874; font-weight: bold;">local</span> <span style="color: #007800;">VAR</span>=<span style="color: #ff0000;">&quot;local variable&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span>
<span style="color: #c20cb9; font-weight: bold;">bash</span>
<span style="color: #666666; font-style: italic;"># Note the bash global variable did not change</span>
<span style="color: #666666; font-style: italic;"># &quot;local&quot; is bash reserved word</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span></pre></td></tr></table></div>

<p><img title="Global vs. &#13;&#10;Local Bash variables in bash script" border="0" alt="Global vs. Local Bash variables in bash script" src="http://zhuwenhao.com/wp-content/uploads/HLIC/5e6e695afe1319820dfbcfbd385c93a4.gif" width="190" height="69" /></p>
<h3>4. Passing arguments to the bash script</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code113'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339113"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p339code113"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Define bash global variable</span>
<span style="color: #666666; font-style: italic;">#This variable is global and can be used anywhere in this bash script</span>
<span style="color: #007800;">VAR</span>=<span style="color: #ff0000;">&quot;global variable&quot;</span>
<span style="color: #000000; font-weight: bold;">function</span> <span style="color: #c20cb9; font-weight: bold;">bash</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
<span style="color: #666666; font-style: italic;">#Define bash local variable</span>
<span style="color: #666666; font-style: italic;">#This variable is local to bash function only</span>
<span style="color: #7a0874; font-weight: bold;">local</span> <span style="color: #007800;">VAR</span>=<span style="color: #ff0000;">&quot;local variable&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span>
<span style="color: #c20cb9; font-weight: bold;">bash</span>
<span style="color: #666666; font-style: italic;"># Note the bash global variable did not change</span>
<span style="color: #666666; font-style: italic;"># &quot;local&quot; is bash reserved word</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$VAR</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code114'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339114"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code114"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>arguments.sh Bash Scripting Tutorial</pre></td></tr></table></div>

<p><img title="Passing arguments to the bash &#13;&#10;script" border="0" alt="Passing &#13;&#10;arguments to the bash script" src="http://zhuwenhao.com/wp-content/uploads/HLIC/77fc446d6486a9fd3796be51f3967507.gif" width="472" height="82" /></p>
<h3>5. Executing shell commands with bash</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code115'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339115"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p339code115"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># use backticks &quot; ` ` &quot; to execute shell command</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">uname</span> -o<span style="color: #000000; font-weight: bold;">`</span>
<span style="color: #666666; font-style: italic;"># executing bash command without backticks</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #c20cb9; font-weight: bold;">uname</span> <span style="color: #660033;">-o</span></pre></td></tr></table></div>

<p><img title="Executing shell commands&#13;&#10; with bash" border="0" alt="Executing shell commands with bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/7d9ae9ca9467d410266bd2112edcc0d9.gif" width="220" height="82" /></p>
<h3>6. Reading User Input</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code116'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339116"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code" id="p339code116"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;Hi, please type the word: \c &quot;</span>
<span style="color: #c20cb9; font-weight: bold;">read</span>  word
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;The word you entered is: <span style="color: #007800;">$word</span>&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;Can you please enter two words? &quot;</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> word1 word2
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Here is your input: <span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #007800;">$word1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> <span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #007800;">$word2</span><span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;How do you feel about bash scripting? &quot;</span>
<span style="color: #666666; font-style: italic;"># read command now stores a reply into the default build-in variable $REPLY</span>
<span style="color: #c20cb9; font-weight: bold;">read</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You said <span style="color: #007800;">$REPLY</span>, I'm glad to hear that! &quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;What are your favorite colours ? &quot;</span>
<span style="color: #666666; font-style: italic;"># -a makes read command to read into an array</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> <span style="color: #660033;">-a</span> colours
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;My favorite colours are also <span style="color: #007800;">${colours[0]}</span>, <span style="color: #007800;">${colours[1]}</span> and <span style="color: #007800;">${colours[2]}</span>:-)&quot;</span></pre></td></tr></table></div>

<p><img title="Reading User Input with bash" border="0" alt="Reading User &#13;&#10;Input with bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/08106ad44d62d1a6419ad99bb577ab60.gif" width="322" height="173" /></p>
<h3>7. Bash Trap Command</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code117'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339117"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code" id="p339code117"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># bash trap command</span>
<span style="color: #7a0874; font-weight: bold;">trap</span> bashtrap INT
<span style="color: #666666; font-style: italic;"># bash clear screen command</span>
<span style="color: #c20cb9; font-weight: bold;">clear</span>;
<span style="color: #666666; font-style: italic;"># bash trap function is executed when CTRL-C is pressed:</span>
<span style="color: #666666; font-style: italic;"># bash prints message =&gt; Executing bash trap subrutine !</span>
bashtrap<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#123;</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;CTRL+C Detected !...executing bash trap !&quot;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #666666; font-style: italic;"># for loop from 1/10 to 10/10</span>
<span style="color: #000000; font-weight: bold;">for</span> a <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">seq</span> <span style="color: #000000;">1</span> <span style="color: #000000;">10</span><span style="color: #000000; font-weight: bold;">`</span>; <span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$a</span>/10 to Exit.&quot;</span> 
    <span style="color: #c20cb9; font-weight: bold;">sleep</span> <span style="color: #000000;">1</span>;
<span style="color: #000000; font-weight: bold;">done</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Exit Bash Trap Example!!!&quot;</span></pre></td></tr></table></div>

<h3>8. Arrays</h3>
<h4>8.1. Declare simple bash array</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code118'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339118"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p339code118"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Declare array with 4 elements</span>
<span style="color: #007800;">ARRAY</span>=<span style="color: #7a0874; font-weight: bold;">&#40;</span> <span style="color: #ff0000;">'Debian Linux'</span> <span style="color: #ff0000;">'Redhat Linux'</span> Ubuntu Linux <span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #666666; font-style: italic;"># get number of elements in the array</span>
<span style="color: #007800;">ELEMENTS</span>=<span style="color: #800000;">${#ARRAY[@]}</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># echo each element in array </span>
<span style="color: #666666; font-style: italic;"># for loop</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span> <span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>;i<span style="color: #000000; font-weight: bold;">&lt;</span><span style="color: #007800;">$ELEMENTS</span>;i++<span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>; <span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #800000;">${ARRAY[${i}</span><span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Declare simple bash array" border="0" alt="Declare simple bash array" src="http://zhuwenhao.com/wp-content/uploads/HLIC/1ccb908a13e9bb40850eaeeb2e038555.gif" width="154" height="82" /></p>
<h4>8.2. Read file into bash array</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code119'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339119"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p339code119"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Declare array</span>
 <span style="color: #7a0874; font-weight: bold;">declare</span> <span style="color: #660033;">-a</span> ARRAY
<span style="color: #666666; font-style: italic;">#Open file for reading to array</span>
<span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #000000;">10</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">count</span>=<span style="color: #000000;">0</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> LINE <span style="color: #000000; font-weight: bold;">&lt;&amp;</span><span style="color: #000000;">10</span>; <span style="color: #000000; font-weight: bold;">do</span>
&nbsp;
    ARRAY<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #007800;">$count</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>=<span style="color: #007800;">$LINE</span>
    <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>count++<span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> Number of elements: <span style="color: #800000;">${#ARRAY[@]}</span>
<span style="color: #666666; font-style: italic;"># echo array's content</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #800000;">${ARRAY[@]}</span>
<span style="color: #666666; font-style: italic;"># close file </span>
<span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #000000;">10</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span>-</pre></td></tr></table></div>

<p><img title="Read file into bash array" border="0" alt="Read file into bash&#13;&#10; array" src="http://zhuwenhao.com/wp-content/uploads/HLIC/437c1b0937f439c86352ea1d879f4872.gif" width="232" height="121" /></p>
<h3>9. Bash if / else / fi statements</h3>
<h4>9.1. Simple Bash if/else statement</h4>
<p>Please note the spacing inside the [ and ] brackets! Without the spaces, it won&#8217;t work! </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code120'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339120"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p339code120"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #007800;">directory</span>=<span style="color: #ff0000;">&quot;./BashScripting&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash check if directory exists</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-d</span> <span style="color: #007800;">$directory</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Directory exists&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Directory does not exists&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash if else fi statement" border="0" alt="Bash if else fi &#13;&#10;statement" src="http://zhuwenhao.com/wp-content/uploads/HLIC/112551431e9bc88ffac74229de5b517b.gif" width="232" height="82" /></p>
<h4>9.2. Nested if/else</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code121'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339121"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code" id="p339code121"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># Declare variable choice and assign value 4</span>
<span style="color: #007800;">choice</span>=<span style="color: #000000;">4</span>
<span style="color: #666666; font-style: italic;"># Print to stdout</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;1. Bash&quot;</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;2. Scripting&quot;</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;3. Tutorial&quot;</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Please choose a word [1,2 or 3]? &quot;</span>
<span style="color: #666666; font-style: italic;"># Loop while the variable choice is equal 4</span>
<span style="color: #666666; font-style: italic;"># bash while loop</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$choice</span> <span style="color: #660033;">-eq</span> <span style="color: #000000;">4</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">do</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># read user input</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> choice
<span style="color: #666666; font-style: italic;"># bash nested if/else</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$choice</span> <span style="color: #660033;">-eq</span> <span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span> ; <span style="color: #000000; font-weight: bold;">then</span>
&nbsp;
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You have chosen word: Bash&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">else</span>                   
&nbsp;
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$choice</span> <span style="color: #660033;">-eq</span> <span style="color: #000000;">2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span> ; <span style="color: #000000; font-weight: bold;">then</span>
                 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You have chosen word: Scripting&quot;</span>
        <span style="color: #000000; font-weight: bold;">else</span>
&nbsp;
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$choice</span> <span style="color: #660033;">-eq</span> <span style="color: #000000;">3</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span> ; <span style="color: #000000; font-weight: bold;">then</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You have chosen word: Tutorial&quot;</span>
                <span style="color: #000000; font-weight: bold;">else</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Please make a choice between 1-3 !&quot;</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;1. Bash&quot;</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;2. Scripting&quot;</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;3. Tutorial&quot;</span>
                        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Please choose a word [1,2 or 3]? &quot;</span>
                        <span style="color: #007800;">choice</span>=<span style="color: #000000;">4</span>
                <span style="color: #000000; font-weight: bold;">fi</span>   
        <span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Nested Bash if else statement" border="0" alt="Nested Bash if&#13;&#10; else statement" src="http://zhuwenhao.com/wp-content/uploads/HLIC/97f0aa3e6d9cfdf75b13ae8a247d8c05.gif" width="232" height="160" /></p>
<h3>10. Bash Comparisons</h3>
<h4>10.1. Arithmetic Comparisons</h4>
<table border="1" cellspacing="0" cellpadding="2" width="100">
<tbody>
<tr>
<td valign="top" width="50">-lt</td>
<td valign="top" width="50">&lt;</td>
</tr>
<tr>
<td valign="top" width="50">-gt </td>
<td valign="top" width="50">&gt;</td>
</tr>
<tr>
<td valign="top" width="50">-le</td>
<td valign="top" width="50">&lt;=</td>
</tr>
<tr>
<td valign="top" width="50">-ge</td>
<td valign="top" width="50">&gt;=</td>
</tr>
<tr>
<td valign="top" width="50">-eq</td>
<td valign="top" width="50">==</td>
</tr>
<tr>
<td valign="top" width="50">-ne </td>
<td valign="top" width="50">!=</td>
</tr>
</tbody>
</table>
<p>&#160;</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code122'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339122"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p339code122"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># declare integers</span>
<span style="color: #007800;">NUM1</span>=<span style="color: #000000;">2</span>
<span style="color: #007800;">NUM2</span>=<span style="color: #000000;">2</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$NUM1</span> <span style="color: #660033;">-eq</span> <span style="color: #007800;">$NUM2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Both Values are equal&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Values are NOT equal&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash Arithmetic Comparisons" border="0" alt="Bash &#13;&#10;Arithmetic Comparisons" src="http://zhuwenhao.com/wp-content/uploads/HLIC/b721db3346dc7dbf37f67d0f85fbbc84.gif" width="484" height="43" /></p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code123'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339123"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p339code123"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#</span>
<span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># declare integers</span>
<span style="color: #007800;">NUM1</span>=<span style="color: #000000;">2</span>
<span style="color: #007800;">NUM2</span>=<span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$NUM1</span> <span style="color: #660033;">-eq</span> <span style="color: #007800;">$NUM2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Both Values are equal&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Values are NOT equal&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash Arithmetic &#13;&#10;Comparisons - values are NOT equal" border="0" alt="Bash &#13;&#10;Arithmetic Comparisons - values are NOT equal" src="http://zhuwenhao.com/wp-content/uploads/HLIC/fbe06f5314e7327ab178ad2131382c59.gif" width="484" height="43" /></p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code124'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339124"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p339code124"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># declare integers</span>
<span style="color: #007800;">NUM1</span>=<span style="color: #000000;">2</span>
<span style="color: #007800;">NUM2</span>=<span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">if</span>   <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$NUM1</span> <span style="color: #660033;">-eq</span> <span style="color: #007800;">$NUM2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Both Values are equal&quot;</span>
<span style="color: #000000; font-weight: bold;">elif</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$NUM1</span> <span style="color: #660033;">-gt</span> <span style="color: #007800;">$NUM2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;NUM1 is greater then NUM2&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;NUM2 is greater then NUM1&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash Arithmetic &#13;&#10;Comparisons - greater then" border="0" alt="Bash Arithmetic Comparisons - greater then" src="http://zhuwenhao.com/wp-content/uploads/HLIC/04627a98974dd894a6485dac8504529b.gif" width="370" height="43" /></p>
<h4>10.2. String Comparisons</h4>
<table border="1" cellspacing="0" cellpadding="2" width="244">
<tbody>
<tr>
<td valign="top" width="64">= </td>
<td valign="top" width="178">equal</td>
</tr>
<tr>
<td valign="top" width="64">!= </td>
<td valign="top" width="178">not equal</td>
</tr>
<tr>
<td valign="top" width="64">&lt; </td>
<td valign="top" width="178">less then</td>
</tr>
<tr>
<td valign="top" width="64">&gt;</td>
<td valign="top" width="178">greater then</td>
</tr>
<tr>
<td valign="top" width="64">-n s1</td>
<td valign="top" width="178">string s1 is not empty</td>
</tr>
<tr>
<td valign="top" width="64">-z s1</td>
<td valign="top" width="178">string s1 is empty</td>
</tr>
</tbody>
</table>
<p>&#160;</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code125'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339125"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p339code125"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Declare string S1</span>
<span style="color: #007800;">S1</span>=<span style="color: #ff0000;">&quot;Bash&quot;</span>
<span style="color: #666666; font-style: italic;">#Declare string S2</span>
<span style="color: #007800;">S2</span>=<span style="color: #ff0000;">&quot;Scripting&quot;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$S1</span> = <span style="color: #007800;">$S2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Both Strings are equal&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Strings are NOT equal&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash String &#13;&#10;Comparisons - values are NOT equal" border="0" alt="Bash String Comparisons - values are NOT equal" src="http://zhuwenhao.com/wp-content/uploads/HLIC/f1f6b5b83ab442790d6a0cb6353475a4.gif" width="370" height="43" /></p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code126'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339126"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p339code126"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;">#Declare string S1</span>
<span style="color: #007800;">S1</span>=<span style="color: #ff0000;">&quot;Bash&quot;</span>
<span style="color: #666666; font-style: italic;">#Declare string S2</span>
<span style="color: #007800;">S2</span>=<span style="color: #ff0000;">&quot;Bash&quot;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$S1</span> = <span style="color: #007800;">$S2</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Both Strings are equal&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Strings are NOT equal&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Locate a Bash Interpreter" border="0" alt="bash &#13;&#10;interpreter location: /bin/bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/fd94227f1a2a864b5317cdef6bec2201.gif" width="370" height="43" /></p>
<h3>11. Bash File Testing</h3>
<table border="1" cellspacing="0" cellpadding="2" width="539">
<tbody>
<tr>
<td valign="top" width="134">-b filename</td>
<td valign="top" width="403">Block special file</td>
</tr>
<tr>
<td valign="top" width="134">-c filename</td>
<td valign="top" width="403">Special character file</td>
</tr>
<tr>
<td valign="top" width="134">-d directoryname</td>
<td valign="top" width="403">Check for directory existence</td>
</tr>
<tr>
<td valign="top" width="134">-e filename</td>
<td valign="top" width="403">Check for file existence</td>
</tr>
<tr>
<td valign="top" width="134">-f filename</td>
<td valign="top" width="403">Check for regular file existence not a directory</td>
</tr>
<tr>
<td valign="top" width="134">-G filename</td>
<td valign="top" width="403">Check if file exists and is owned by effective group ID.</td>
</tr>
<tr>
<td valign="top" width="134">-g filename</td>
<td valign="top" width="403">true if file exists and is set-group-id.</td>
</tr>
<tr>
<td valign="top" width="134">-k filename</td>
<td valign="top" width="403">Sticky bit</td>
</tr>
<tr>
<td valign="top" width="134">-L filename</td>
<td valign="top" width="403">Symbolic link</td>
</tr>
<tr>
<td valign="top" width="134">-O filename</td>
<td valign="top" width="403">True if file exists and is owned by the effective user id.</td>
</tr>
<tr>
<td valign="top" width="134">-r filename</td>
<td valign="top" width="403">Check if file is a readable</td>
</tr>
<tr>
<td valign="top" width="134">-S filename</td>
<td valign="top" width="403">Check if file is socket</td>
</tr>
<tr>
<td valign="top" width="134">-s filename</td>
<td valign="top" width="403">Check if file is nonzero size</td>
</tr>
<tr>
<td valign="top" width="134">-u filename</td>
<td valign="top" width="403">Check if file set-ser-id bit is set</td>
</tr>
<tr>
<td valign="top" width="134">-w filename</td>
<td valign="top" width="403">Check if file is writable</td>
</tr>
<tr>
<td valign="top" width="134">-x filename</td>
<td valign="top" width="403">Check if file is executable</td>
</tr>
</tbody>
</table>
<p>&#160;</p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code127'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339127"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p339code127"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #007800;">file</span>=<span style="color: #ff0000;">&quot;./file&quot;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-e</span> <span style="color: #007800;">$file</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;File exists&quot;</span>
<span style="color: #000000; font-weight: bold;">else</span> 
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;File does not exists&quot;</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></td></tr></table></div>

<p><img title="Bash File Testing - File does&#13;&#10; not exist" border="0" alt="Bash &#13;&#10;File Testing - File does not exist" src="http://zhuwenhao.com/wp-content/uploads/HLIC/17f4ed69b54e9c09978b607eb523ed99.gif" width="370" height="43" /> <img title="Bash File Testing - File exists" border="0" alt="Bash File &#13;&#10;Testing - File exists" src="http://zhuwenhao.com/wp-content/uploads/HLIC/253cb30c2c29322e7d35facb8e47c124.gif" width="370" height="82" /></p>
<p>Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator &quot;!&quot; which negates the -e option. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code128'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339128"><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" id="p339code128"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #000000; font-weight: bold;">!</span> <span style="color: #660033;">-e</span> myfile <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">do</span>
<span style="color: #666666; font-style: italic;"># Sleep until file does exists/is created</span>
<span style="color: #c20cb9; font-weight: bold;">sleep</span> <span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<h3>12. Loops</h3>
<h4>12.1. Bash for loop</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code129'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339129"><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" id="p339code129"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash for loop</span>
<span style="color: #000000; font-weight: bold;">for</span> f <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span> <span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span> <span style="color: #7a0874; font-weight: bold;">&#41;</span>; <span style="color: #000000; font-weight: bold;">do</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$f</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p>Running for loop from bash shell command line: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code130'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339130"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code130"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">for</span> f <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span> <span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span> <span style="color: #7a0874; font-weight: bold;">&#41;</span>; <span style="color: #000000; font-weight: bold;">do</span> <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$f</span>; <span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Bash for &#13;&#10;loop" border="0" alt="Bash for loop" src="http://zhuwenhao.com/wp-content/uploads/HLIC/3d23e6cc5766905da4d6e945d4193a5e.gif" width="484" height="173" /></p>
<h4>12.2. Bash while loop</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code131'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339131"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p339code131"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #007800;">COUNT</span>=<span style="color: #000000;">6</span>
<span style="color: #666666; font-style: italic;"># bash while loop</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$COUNT</span> <span style="color: #660033;">-gt</span> <span style="color: #000000;">0</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">do</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> Value of count is: <span style="color: #007800;">$COUNT</span>
	<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">COUNT</span>=COUNT-<span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Bash &#13;&#10;while loop" border="0" alt="Bash while loop" src="http://zhuwenhao.com/wp-content/uploads/HLIC/6e00adae0a4e0d25b438b0352a2fae8c.gif" width="484" height="108" /></p>
<h4>12.3. Bash until loop</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code132'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339132"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p339code132"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #007800;">COUNT</span>=<span style="color: #000000;">0</span>
<span style="color: #666666; font-style: italic;"># bash until loop</span>
<span style="color: #000000; font-weight: bold;">until</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$COUNT</span> <span style="color: #660033;">-gt</span> <span style="color: #000000;">5</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">do</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> Value of count is: <span style="color: #007800;">$COUNT</span>
        <span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">COUNT</span>=COUNT+<span style="color: #000000;">1</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Bash &#13;&#10;until loop" border="0" alt="Bash until loop" src="http://zhuwenhao.com/wp-content/uploads/HLIC/0481db366dc78dae0a33bda6c03fe6ed.gif" width="484" height="108" /></p>
<h4>12.4. Control bash loop with </h4>
<p>Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code133'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339133"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code" id="p339code133"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># This bash script will locate and replace spaces</span>
<span style="color: #666666; font-style: italic;"># in the filenames</span>
<span style="color: #007800;">DIR</span>=<span style="color: #ff0000;">&quot;.&quot;</span>
<span style="color: #666666; font-style: italic;"># Controlling a loop with bash read command by redirecting STDOUT as</span>
<span style="color: #666666; font-style: italic;"># a STDIN to while loop</span>
<span style="color: #666666; font-style: italic;"># find will not truncate filenames containing spaces</span>
<span style="color: #c20cb9; font-weight: bold;">find</span> <span style="color: #007800;">$DIR</span> <span style="color: #660033;">-type</span> f <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> <span style="color: #c20cb9; font-weight: bold;">file</span>; <span style="color: #000000; font-weight: bold;">do</span>
<span style="color: #666666; font-style: italic;"># using POSIX class [:space:] to find space in the filename</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$file</span>&quot;</span> = <span style="color: #000000; font-weight: bold;">*</span><span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span>:space:<span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #000000; font-weight: bold;">*</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>; <span style="color: #000000; font-weight: bold;">then</span>
<span style="color: #666666; font-style: italic;"># substitute space with &quot;_&quot; character and consequently rename the file</span>
<span style="color: #c20cb9; font-weight: bold;">mv</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$file</span>&quot;</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$file</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">tr</span> <span style="color: #ff0000;">' '</span> <span style="color: #ff0000;">'_'</span><span style="color: #000000; font-weight: bold;">`</span>
<span style="color: #000000; font-weight: bold;">fi</span>;
<span style="color: #666666; font-style: italic;"># end of while loop</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Bash script to replace&#13;&#10; spaces in the filenames with _" border="0" alt="Bash script &#13;&#10;to replace spaces in the filenames with _" src="http://zhuwenhao.com/wp-content/uploads/HLIC/7c098d41f4f65fc2ce845a30f382549c.gif" width="442" height="160" /></p>
<h3>13. Bash Functions</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code134'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339134"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p339code134"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">!/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">bash</span>
<span style="color: #666666; font-style: italic;"># BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER</span>
<span style="color: #000000; font-weight: bold;">function</span> function_B <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> Function B.
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> function_A <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$1</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> function_D <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> Function D.
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> function_C <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$1</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #666666; font-style: italic;"># FUNCTION CALLS</span>
<span style="color: #666666; font-style: italic;"># Pass parameter to function A</span>
function_A <span style="color: #ff0000;">&quot;Function A.&quot;</span>
function_B
<span style="color: #666666; font-style: italic;"># Pass parameter to function C</span>
function_C <span style="color: #ff0000;">&quot;Function C.&quot;</span>
function_D</pre></td></tr></table></div>

<p><img title="Bash &#13;&#10;Functions" border="0" alt="Bash Functions" src="http://zhuwenhao.com/wp-content/uploads/HLIC/1715a494be3c75154d84be2d17856678.gif" width="484" height="82" /></p>
<h3>14. Bash Select</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code135'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339135"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code" id="p339code135"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #007800;">PS3</span>=<span style="color: #ff0000;">'Choose one word: '</span> 
&nbsp;
<span style="color: #666666; font-style: italic;"># bash select</span>
<span style="color: #000000; font-weight: bold;">select</span> word <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #ff0000;">&quot;linux&quot;</span> <span style="color: #ff0000;">&quot;bash&quot;</span> <span style="color: #ff0000;">&quot;scripting&quot;</span> <span style="color: #ff0000;">&quot;tutorial&quot;</span> 
<span style="color: #000000; font-weight: bold;">do</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;The word you have selected is: <span style="color: #007800;">$word</span>&quot;</span>
<span style="color: #666666; font-style: italic;"># Break, otherwise endless loop</span>
  <span style="color: #7a0874; font-weight: bold;">break</span>  
<span style="color: #000000; font-weight: bold;">done</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">0</span></pre></td></tr></table></div>

<p><img title="Bash Select" border="0" alt="Bash Select" src="http://zhuwenhao.com/wp-content/uploads/HLIC/bcb1e849a412444f2fbcf3a7308cfcf2.gif" width="214" height="108" /></p>
<h3>15. Case statement conditional</h3>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code136'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339136"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p339code136"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;What is your preferred programming / scripting language&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;1) bash&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;2) perl&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;3) phyton&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;4) c++&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;5) I do not know !&quot;</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> <span style="color: #000000; font-weight: bold;">case</span>;
<span style="color: #666666; font-style: italic;">#simple case bash structure</span>
<span style="color: #666666; font-style: italic;"># note in this case $case is variable and does not have to</span>
<span style="color: #666666; font-style: italic;"># be named case this is just an example</span>
<span style="color: #000000; font-weight: bold;">case</span> <span style="color: #007800;">$case</span> <span style="color: #000000; font-weight: bold;">in</span>
    <span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You selected bash&quot;</span><span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You selected perl&quot;</span><span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000;">3</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You selected phyton&quot;</span><span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000;">4</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;You selected c++&quot;</span><span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000;">5</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">exit</span>
<span style="color: #000000; font-weight: bold;">esac</span></pre></td></tr></table></div>

<p><img title="bash case statement conditiona" border="0" alt="bash case statement &#13;&#10;conditiona" src="http://zhuwenhao.com/wp-content/uploads/HLIC/4786877f23908eb04883776adde01218.gif" width="340" height="134" /></p>
<h3>16. Bash quotes and quotations</h3>
<p>Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics. </p>
<h4>16.1. Escaping Meta characters</h4>
<p>Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash &quot;\&quot; character. Example: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code137'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339137"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code" id="p339code137"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #666666; font-style: italic;">#Declare bash string variable</span>
<span style="color: #007800;">BASH_VAR</span>=<span style="color: #ff0000;">&quot;Bash Script&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># echo variable BASH_VAR</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$BASH_VAR</span>
&nbsp;
<span style="color: #666666; font-style: italic;">#when meta character such us &quot;$&quot; is escaped with &quot;\&quot; it will be read literally</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> \<span style="color: #007800;">$BASH_VAR</span> 
&nbsp;
<span style="color: #666666; font-style: italic;"># backslash has also special meaning and it can be suppressed with yet another &quot;\&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;\<span style="color: #000099; font-weight: bold;">\&quot;</span></span></pre></td></tr></table></div>

<p><img title="escaping meta characters in bash" border="0" alt="escaping meta characters in &#13;&#10;bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/b0de260409d3d1029209f36eea711844.gif" width="202" height="69" /></p>
<h4>16.2. Single quotes</h4>
<p>Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code138'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339138"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p339code138"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
 <span style="color: #666666; font-style: italic;">#Declare bash string variable</span>
 <span style="color: #007800;">BASH_VAR</span>=<span style="color: #ff0000;">&quot;Bash Script&quot;</span>
&nbsp;
 <span style="color: #666666; font-style: italic;"># echo variable BASH_VAR</span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$BASH_VAR</span>
&nbsp;
 <span style="color: #666666; font-style: italic;"># meta characters special meaning in bash is suppressed when  using single quotes </span>
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'$BASH_VAR  &quot;$BASH_VAR&quot;'</span></pre></td></tr></table></div>

<p><img title="Using single quotes in bash" border="0" alt="Using single quotes in &#13;&#10;bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/7db79df46a83eb27d201dec0eaebb011.gif" width="214" height="56" /></p>
<h4>16.3. Double Quotes</h4>
<p>Double quotes in bash will suppress special meaning of every meta characters except &quot;$&quot;, &quot;\&quot; and &quot;`&quot;. Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with &quot;\&quot;. Example: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code139'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339139"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p339code139"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #666666; font-style: italic;">#Declare bash string variable</span>
<span style="color: #007800;">BASH_VAR</span>=<span style="color: #ff0000;">&quot;Bash Script&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># echo variable BASH_VAR</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$BASH_VAR</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># meta characters and its special meaning in bash is </span>
<span style="color: #666666; font-style: italic;"># suppressed when using double quotes except &quot;$&quot;, &quot;\&quot; and &quot;`&quot;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;It's <span style="color: #007800;">$BASH_VAR</span>  and <span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #007800;">$BASH_VAR</span><span style="color: #000099; font-weight: bold;">\&quot;</span> using backticks: <span style="color: #780078;">`date`</span>&quot;</span></pre></td></tr></table></div>

<p><img title="Using double quotes in bash" border="0" alt="Using double quotes in &#13;&#10;bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/513679ef8fd8955eb85d12e3ceb9eabd.gif" width="490" height="56" /></p>
<h4>16.4. Bash quoting with ANSI-C style</h4>
<p>There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with &quot;\&quot; will gain special meaning according to the ANSI-C standard. </p>
<table border="1" cellspacing="0" cellpadding="2" width="702">
<tbody>
<tr>
<td valign="top" width="31">/a</td>
<td valign="top" width="326">alert (bell)</td>
<td valign="top" width="16">/b</td>
<td valign="top" width="327">backspace</td>
</tr>
<tr>
<td valign="top" width="31">/e</td>
<td valign="top" width="326">an escape character</td>
<td valign="top" width="16">/f</td>
<td valign="top" width="327">form feed</td>
</tr>
<tr>
<td valign="top" width="31">/n</td>
<td valign="top" width="326">newline</td>
<td valign="top" width="16">/r</td>
<td valign="top" width="327">carriage return</td>
</tr>
<tr>
<td valign="top" width="31">/t</td>
<td valign="top" width="326">horizontal tab</td>
<td valign="top" width="16">/v</td>
<td valign="top" width="327">vertical tab</td>
</tr>
<tr>
<td valign="top" width="31">\\</td>
<td valign="top" width="326">backslash</td>
<td valign="top" width="16">\`</td>
<td valign="top" width="327">single quote</td>
</tr>
<tr>
<td valign="top" width="31">\nnn</td>
<td valign="top" width="326">octal value of characters ( see [http://www.asciitable.com/ ASCII table] )</td>
<td valign="top" width="16">\xnn</td>
<td valign="top" width="327">hexadecimal value of characters ( see [http://www.asciitable.com/ ASCII table] )</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>The syntax fo ansi-c bash quoting is: $” . Here is an example: </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code140'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339140"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p339code140"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># as a example we have used \n as a new line, \x40 is hex value for @</span>
<span style="color: #666666; font-style: italic;"># and \56 is octal value for .</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> $<span style="color: #ff0000;">'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org'</span></pre></td></tr></table></div>

<p><img title="quoting in bash with ansi-c stype" border="0" alt="quoting in bash with ansi-c &#13;&#10;stype" src="http://zhuwenhao.com/wp-content/uploads/HLIC/6eb9043058d8b18cbd9c1824179b4f21.gif" width="202" height="56" /></p>
<h3>17. Arithmetic Operations</h3>
<h4>17.1. Bash Addition Calculator Example</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code141'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339141"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p339code141"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">RESULT1</span>=<span style="color: #007800;">$1</span>+<span style="color: #007800;">$2</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$1</span>+<span style="color: #007800;">$2</span>=<span style="color: #007800;">$RESULT1</span> <span style="color: #ff0000;">' -&gt; # let RESULT1=$1+$2'</span>
<span style="color: #7a0874; font-weight: bold;">declare</span> <span style="color: #660033;">-i</span> RESULT2
<span style="color: #007800;">RESULT2</span>=<span style="color: #007800;">$1</span>+<span style="color: #007800;">$2</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$1</span>+<span style="color: #007800;">$2</span>=<span style="color: #007800;">$RESULT2</span> <span style="color: #ff0000;">' -&gt; # declare -i RESULT2; RESULT2=$1+$2'</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$1</span>+<span style="color: #007800;">$2</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #007800;">$1</span> + <span style="color: #007800;">$2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #ff0000;">' -&gt; # $(($1 + $2))'</span></pre></td></tr></table></div>

<p><img title="Bash Addition Calculator" border="0" alt="Bash Addition Calculator" src="http://zhuwenhao.com/wp-content/uploads/HLIC/407b4a7ba59f8f7133611479c94e95c1.gif" width="304" height="69" /></p>
<h4>17.2. Bash Arithmetics</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code142'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339142"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="code" id="p339code142"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'### let ###'</span>
<span style="color: #666666; font-style: italic;"># bash addition</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">ADDITION</span>=<span style="color: #000000;">3</span>+<span style="color: #000000;">5</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;3 + 5 =&quot;</span> <span style="color: #007800;">$ADDITION</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash subtraction</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">SUBTRACTION</span>=<span style="color: #000000;">7</span>-<span style="color: #000000;">8</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;7 - 8 =&quot;</span> <span style="color: #007800;">$SUBTRACTION</span> 
&nbsp;
<span style="color: #666666; font-style: italic;"># bash multiplication</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">MULTIPLICATION</span>=<span style="color: #000000;">5</span><span style="color: #000000; font-weight: bold;">*</span><span style="color: #000000;">8</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;5 * 8 =&quot;</span> <span style="color: #007800;">$MULTIPLICATION</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash division</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">DIVISION</span>=<span style="color: #000000;">4</span><span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">2</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;4 / 2 =&quot;</span> <span style="color: #007800;">$DIVISION</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash modulus</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">MODULUS</span>=<span style="color: #000000;">9</span><span style="color: #000000; font-weight: bold;">%</span>4
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;9 % 4 =&quot;</span> <span style="color: #007800;">$MODULUS</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash power of two</span>
<span style="color: #7a0874; font-weight: bold;">let</span> <span style="color: #007800;">POWEROFTWO</span>=<span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">**</span><span style="color: #000000;">2</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;2 ^ 2 =&quot;</span> <span style="color: #007800;">$POWEROFTWO</span>
&nbsp;
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'### Bash Arithmetic Expansion ###'</span>
<span style="color: #666666; font-style: italic;"># There are two formats for arithmetic expansion: $[ expression ] </span>
<span style="color: #666666; font-style: italic;"># and $(( expression #)) its your choice which you use</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">4</span> + <span style="color: #000000;">5</span> = $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">4</span> + <span style="color: #000000;">5</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">7</span> - <span style="color: #000000;">7</span> = $<span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #000000;">7</span> - <span style="color: #000000;">7</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">4</span> x <span style="color: #000000;">6</span> = $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">3</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">6</span> <span style="color: #000000; font-weight: bold;">/</span> <span style="color: #000000;">3</span> = $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">6</span> <span style="color: #000000; font-weight: bold;">/</span> <span style="color: #000000;">3</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">8</span> <span style="color: #000000; font-weight: bold;">%</span> <span style="color: #000000;">7</span> = $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">8</span> <span style="color: #000000; font-weight: bold;">%</span> <span style="color: #000000;">7</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #000000;">2</span> ^ <span style="color: #000000;">8</span> = $<span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #000000;">2</span> <span style="color: #000000; font-weight: bold;">**</span> <span style="color: #000000;">8</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
&nbsp;
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'### Declare ###'</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">&quot;Please enter two numbers \c&quot;</span>
<span style="color: #666666; font-style: italic;"># read user input</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> num1 num2
<span style="color: #7a0874; font-weight: bold;">declare</span> <span style="color: #660033;">-i</span> result
<span style="color: #007800;">result</span>=<span style="color: #007800;">$num1</span>+<span style="color: #007800;">$num2</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Result is:<span style="color: #007800;">$result</span> &quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash convert binary number 10001</span>
<span style="color: #007800;">result</span>=<span style="color: #000000;">2</span><span style="color: #666666; font-style: italic;">#10001</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$result</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash convert octal number 16</span>
<span style="color: #007800;">result</span>=<span style="color: #000000;">8</span><span style="color: #666666; font-style: italic;">#16</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$result</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># bash convert hex number 0xE6A</span>
<span style="color: #007800;">result</span>=<span style="color: #000000;">16</span><span style="color: #666666; font-style: italic;">#E6A</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$result</span></pre></td></tr></table></div>

<p><img title="Bash Arithmetic Operations" border="0" alt="Bash Arithmetic &#13;&#10;Operations" src="http://zhuwenhao.com/wp-content/uploads/HLIC/fe12e99a51abda736117c1529e27e4fe.gif" width="262" height="290" /></p>
<h4>17.3. Round floating point number</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code143'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339143"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p339code143"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># get floating point number</span>
<span style="color: #007800;">floating_point_number</span>=<span style="color: #000000;">3.3446</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$floating_point_number</span>
<span style="color: #666666; font-style: italic;"># round floating point number with bash</span>
<span style="color: #000000; font-weight: bold;">for</span> bash_rounded_number <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">printf</span> <span style="color: #000000; font-weight: bold;">%</span>.0f <span style="color: #007800;">$floating_point_number</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>; <span style="color: #000000; font-weight: bold;">do</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Rounded number with bash:&quot;</span> <span style="color: #007800;">$bash_rounded_number</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></td></tr></table></div>

<p><img title="Round floating point number with&#13;&#10; bash" border="0" alt="Round &#13;&#10;floating point number with bash" src="http://zhuwenhao.com/wp-content/uploads/HLIC/637106928c4b70f81dc3d172293e4982.gif" width="178" height="56" /></p>
<h4>17.4. Bash floating point calculations</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code144'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339144"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p339code144"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #666666; font-style: italic;"># Simple linux bash calculator </span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Enter input:&quot;</span> 
<span style="color: #c20cb9; font-weight: bold;">read</span> userinput
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Result with 2 digits after decimal point:&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;scale=2; <span style="color: #007800;">${userinput}</span>&quot;</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">bc</span> 
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Result with 10 digits after decimal point:&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;scale=10; <span style="color: #007800;">${userinput}</span>&quot;</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">bc</span> 
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Result as rounded integer:&quot;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$userinput</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">bc</span></pre></td></tr></table></div>

<p><img title="Bash floating point calculations" border="0" alt="Bash floating point &#13;&#10;calculations" src="http://zhuwenhao.com/wp-content/uploads/HLIC/70aba42cc7621c34256b85420890de61.gif" width="256" height="134" /></p>
<h3>18. Redirections</h3>
<h4>18.1. STDOUT from bash script to STDERR</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code145'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339145"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p339code145"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
 <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Redirect this STDOUT to STDERR&quot;</span> <span style="color: #000000;">1</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">2</span></pre></td></tr></table></div>

<p>To proof that STDOUT is redirected to STDERR we can redirect script&#8217;s output to file:<br />
  <br /><img title="STDOUT from bash script to STDERR" border="0" alt="STDOUT from bash script to &#13;&#10;STDERR" src="http://zhuwenhao.com/wp-content/uploads/HLIC/d690ff886e17e0d3369cd0a9c90d0be5.gif" width="286" height="147" /></p>
<h4>18.2. STDERR from bash script to STDOUT</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code146'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339146"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p339code146"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
 <span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #007800;">$1</span> <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span></pre></td></tr></table></div>

<p>To proof that STDERR is redirected to STDOUT we can redirect script&#8217;s output to file:<br />
  <br /><img title="STDERR from bash script to STDOUT" border="0" alt="STDERR from bash script to &#13;&#10;STDOUT" src="http://zhuwenhao.com/wp-content/uploads/HLIC/5098790c995e2ba672c395b11d75e797.gif" width="358" height="147" /></p>
<h4>18.3. stdout to screen</h4>
<p>The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code147'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339147"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code147"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>proc<span style="color: #000000; font-weight: bold;">/</span>partitions</pre></td></tr></table></div>

<p><img title="bash stdout to screen" border="0" alt="bash stdout to screen" src="http://zhuwenhao.com/wp-content/uploads/HLIC/36b19b9c3b3aa10b64fcd524ec221c4e.gif" width="484" height="121" /></p>
<h4>18.4. stdout to file</h4>
<p>Here we use &quot;&gt;&quot; to redirect stdout to a file &quot;partitions.txt&quot;. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code148'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339148"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code148"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>proc<span style="color: #000000; font-weight: bold;">/</span>partitions <span style="color: #000000; font-weight: bold;">&gt;</span> partitions.txt</pre></td></tr></table></div>

<p><img title="bash stdout to file" border="0" alt="bash stdout to file" src="http://zhuwenhao.com/wp-content/uploads/HLIC/7f7ee48c4dbe394bbdf888f5a46536f2.gif" width="484" height="134" /></p>
<h4>18.5. stderr to file</h4>
<p>In this example you will redirect the standard error ( stderr ) to a file and stdout to a default screen. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code149'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339149"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code149"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-r</span> hda6 <span style="color: #000000; font-weight: bold;">*</span> . <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;</span> stderr.txt</pre></td></tr></table></div>

<p><img title="bash stderr to file" border="0" alt="bash stderr to file" src="http://zhuwenhao.com/wp-content/uploads/HLIC/b21c2271625b1e973e7468ba866faf32.gif" width="484" height="251" /></p>
<h4>18.6. stdout to stderr</h4>
<p>In this case the output of a command will be written to the same descriptor as a stderr. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code150'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339150"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code150"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-r</span> hda6 <span style="color: #000000; font-weight: bold;">*</span> . <span style="color: #000000;">1</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">2</span> stderr.txt</pre></td></tr></table></div>

<p><img title="bash stdout to stderr" border="0" alt="bash stdout to stderr" src="http://zhuwenhao.com/wp-content/uploads/HLIC/700b9fe7e49c7cb9eb8731d1cf337dac.gif" width="484" height="225" /></p>
<h4>18.7. stderr to stdout</h4>
<p>In this case the stderr of a command will be written to the same descriptor as a stdout. </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code151'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339151"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code151"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-r</span> hda6 <span style="color: #000000; font-weight: bold;">*</span> . <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span> stderr.txt</pre></td></tr></table></div>

<p><img title="bash stderr to stdout" border="0" alt="bash stderr to stdout" src="http://zhuwenhao.com/wp-content/uploads/HLIC/ce9781383f648771ea2a4b5507bc4489.gif" width="484" height="225" /></p>
<h4>18.8. stderr and stdout to file</h4>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p339code152'); return false;">View Code</a> BASH</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p339152"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p339code152"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-r</span> hda6 <span style="color: #000000; font-weight: bold;">*</span> . <span style="color: #000000; font-weight: bold;">&amp;&gt;</span> stderr_and_stdout.txt</pre></td></tr></table></div>

<p><img title="stderr and stdout to file" border="0" alt="stderr and stdout &#13;&#10;to file" src="http://zhuwenhao.com/wp-content/uploads/HLIC/dda4277bc3d3dc1d7c69b7f869eb14b8.gif" width="484" height="251" /></p>
]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/339/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/bash/bash-scripting-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>提出一种高精度延迟函数的实现，欢迎交流</title>
		<link>http://zhuwenhao.com/238/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e6%8f%90%e5%87%ba%e4%b8%80%e7%a7%8d%e9%ab%98%e7%b2%be%e5%ba%a6%e5%bb%b6%e8%bf%9f%e5%87%bd%e6%95%b0%e7%9a%84%e5%ae%9e%e7%8e%b0%ef%bc%8c%e6%ac%a2%e8%bf%8e%e4%ba%a4%e6%b5%81/</link>
		<comments>http://zhuwenhao.com/238/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e6%8f%90%e5%87%ba%e4%b8%80%e7%a7%8d%e9%ab%98%e7%b2%be%e5%ba%a6%e5%bb%b6%e8%bf%9f%e5%87%bd%e6%95%b0%e7%9a%84%e5%ae%9e%e7%8e%b0%ef%bc%8c%e6%ac%a2%e8%bf%8e%e4%ba%a4%e6%b5%81/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 15:02:02 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[Cpp 语言]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/238/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e6%8f%90%e5%87%ba%e4%b8%80%e7%a7%8d%e9%ab%98%e7%b2%be%e5%ba%a6%e5%bb%b6%e8%bf%9f%e5%87%bd%e6%95%b0%e7%9a%84%e5%ae%9e%e7%8e%b0%ef%bc%</guid>
		<description><![CDATA[在Windows系统下，需要延迟一定的时间后继续流程，貌似缺乏这种库函数，MFC提供的延迟函数似乎本质精度无法保证。比如Sleep。在下面提出一种方法，请大家斧正。当然先提出一点，有人认为在Windows系统先不可能获得准确定时，或者把系统挂起来延迟等待不符合多线程编程规范。是的，谢谢您的提醒，但这个讨论中大家就不要再重复这样的观点啦。我们的确需要精确定时，即使我把系统完全占用也在所不惜。不就是几十毫秒嘛  

View Code  [...]]]></description>
			<content:encoded><![CDATA[<p>在Windows系统下，需要延迟一定的时间后继续流程，貌似缺乏这种库函数，MFC提供的延迟函数似乎本质精度无法保证。比如Sleep。在下面提出一种方法，请大家斧正。当然先提出一点，有人认为在Windows系统先不可能获得准确定时，或者把系统挂起来延迟等待不符合多线程编程规范。是的，谢谢您的提醒，但这个讨论中大家就不要再重复这样的观点啦。我们的确需要精确定时，即使我把系统完全占用也在所不惜。不就是几十毫秒嘛 <img src='http://zhuwenhao.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p238code154'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p238154"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
</pre></td><td class="code" id="p238code154"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// 高精度延迟函数 【开发草稿】 Rev 0.01</span>
<span style="color: #ff0000; font-style: italic;">/* 注：MSDN中提到的以下问题，本版本程序并未处理！！
On a multiprocessor computer, it should not matter which processor is called. 
However, you can get different results on different processors due to bugs 
in the basic input/output system (BIOS) or the hardware abstraction layer (HAL).
To specify processor affinity for a thread, use the SetThreadAffinityMask function. 
*/</span>
<span style="color: #0000ff;">int</span> DelayPrecision<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> TimeInMilliSecond<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    LARGE_INTEGER Frequency<span style="color: #008080;">;</span>
    LARGE_INTEGER CountBegin<span style="color: #008080;">;</span>
    LARGE_INTEGER CountNow<span style="color: #008080;">;</span>
    LONGLONG DelayCount<span style="color: #008080;">;</span>
    LONGLONG EndCount<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> QueryPerformanceFrequency<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>Frequency<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">//试算终止计数</span>
        DelayCount <span style="color: #000080;">=</span> Frequency.<span style="color: #007788;">QuadPart</span> <span style="color: #000040;">/</span> <span style="color: #0000dd;">1000</span> <span style="color: #000040;">*</span> TimeInMilliSecond<span style="color: #008080;">;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> QueryPerformanceCounter<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>CountBegin<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            EndCount <span style="color: #000080;">=</span> CountBegin.<span style="color: #007788;">QuadPart</span> <span style="color: #000040;">+</span> DelayCount<span style="color: #008080;">;</span>
            <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>EndCount <span style="color: #000080;">&lt;</span> CountBegin.<span style="color: #007788;">QuadPart</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #666666;">//计数器循环回去了</span>
                <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> QueryPerformanceCounter<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>CountNow<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>CountNow.<span style="color: #007788;">QuadPart</span> <span style="color: #000080;">&lt;</span> CountBegin.<span style="color: #007788;">QuadPart</span> <span style="color: #000040;">&amp;&amp;</span> CountNow.<span style="color: #007788;">QuadPart</span> <span style="color: #000080;">&gt;</span> EndCount<span style="color: #008000;">&#41;</span>
                        <span style="color: #008000;">&#123;</span>
                            <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
                        <span style="color: #008000;">&#125;</span>
                    <span style="color: #008000;">&#125;</span>
                    <span style="color: #0000ff;">else</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0000ff;">else</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #666666;">//一般情况</span>
                <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> QueryPerformanceCounter<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>CountNow<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>CountNow.<span style="color: #007788;">QuadPart</span> <span style="color: #000080;">&gt;</span> EndCount<span style="color: #008000;">&#41;</span>
                        <span style="color: #008000;">&#123;</span>
                            <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span>
                        <span style="color: #008000;">&#125;</span>
                    <span style="color: #008000;">&#125;</span>
                    <span style="color: #0000ff;">else</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">//如果无法使用高精度定时器,拿Sleep凑合着用吧.</span>
    Sleep<span style="color: #008000;">&#40;</span>TimeInMilliSecond<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/238/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e6%8f%90%e5%87%ba%e4%b8%80%e7%a7%8d%e9%ab%98%e7%b2%be%e5%ba%a6%e5%bb%b6%e8%bf%9f%e5%87%bd%e6%95%b0%e7%9a%84%e5%ae%9e%e7%8e%b0%ef%bc%8c%e6%ac%a2%e8%bf%8e%e4%ba%a4%e6%b5%81/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[转载]简单蚁群算法的实现</title>
		<link>http://zhuwenhao.com/157/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e8%bd%ac%e8%bd%bd%e7%ae%80%e5%8d%95%e8%9a%81%e7%be%a4%e7%ae%97%e6%b3%95%e7%9a%84%e5%ae%9e%e7%8e%b0/</link>
		<comments>http://zhuwenhao.com/157/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e8%bd%ac%e8%bd%bd%e7%ae%80%e5%8d%95%e8%9a%81%e7%be%a4%e7%ae%97%e6%b3%95%e7%9a%84%e5%ae%9e%e7%8e%b0/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 04:05:11 +0000</pubDate>
		<dc:creator>朱文昊 Albert Zhu</dc:creator>
				<category><![CDATA[Cpp 语言]]></category>
		<category><![CDATA[计算机科学]]></category>

		<guid isPermaLink="false">http://zhuwenhao.com/157/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e8%bd%ac%e8%bd%bd%e7%ae%80%e5%8d%95%e8%9a%81%e7%be%a4%e7%ae%97%e6%b3%95%e7%9a%84%e5%ae%9e%e7%8e%b0/</guid>
		<description><![CDATA[本文转载自http://blog.chinaunix.net/u1/34560/showart_312651.html
一 引言
蚁群算法(ant colony optimization，ACO)，又称蚂蚁算法，是一种用来在图中寻找优化路径的机率型技术。它由Marco  [...]]]></description>
			<content:encoded><![CDATA[<p>本文转载自<a title="http://blog.chinaunix.net/u1/34560/showart_312651.html" href="http://blog.chinaunix.net/u1/34560/showart_312651.html">http://blog.chinaunix.net/u1/34560/showart_312651.html</a></p>
<p><b>一 </b><b>引言</b></p>
<p>蚁群算法(ant colony optimization，ACO)，又称蚂蚁算法，是一种用来在图中寻找优化路径的机率型技术。它由Marco Dorigo于1992年在他的博士论文中引入，其灵感来源于蚂蚁在寻找食物过程中发现路径的行为。蚁群算法是一种模拟进化算法。初步的研究表明该算法具有许多优良的性质。针对PID控制器参数优化设计问题，将蚁群算法设计的结果与遗传算法设计的结果进行了比较，数值仿真结果表明，蚁群算法具有一种新的模拟进化优化方法的有效性和应用价值。蚁群算法是一种求解组合最优化问题的新型通用启发式方法，该方法具有正反馈、分布式计算和富于建设性的贪婪启发式搜索的特点。正因为蚁群算法有这些优点，很多研究者都在致力研究和改过它，本文的目的正是为了介绍蚁群算法，学习如何编写蚁群算法。</p>
<p><b>二 </b><b>蚁群算法的介绍</b></p>
<p>昆虫世界中，蚂蚁的组成是一种群居的世袭大家庭，我们称之为蚁群。蚂蚁分为世袭制的蚁王（后）和工蚁两种，它们具有高度组织的社会性，彼此沟通不仅可以借助触觉和视觉的联系，在大规模的协调行动中还可以借助外激素（有些书称信息素）之类的信息介质。</p>
<p>首先我们要理解蚂蚁是如何觅食的，蚂蚁平时在巢穴附近作无规则行走，一量发现食物并不立即进食而是将之搬回蚁穴与其它蚂蚁分享，在食物小时则独自搬回蚁穴，否则就回蚁穴搬兵，一路上会留下外激素，食物越大外激素的浓度就越大，越能吸引其它的蚂蚁过去一起搬去食物，这样最终就能将食物全部搬回蚁穴。这个过程用程序实现看似非常复杂，要编写一个“智能”的蚂蚁也看似不太可能，事实上每个蚂蚁只做了非常简单的工作：检查某个范围内有无食物，并逐渐向外激素浓的方向运动。简而言之，蚁群运动无非是同时反复执行多个简单规则而已。下面详细说明蚁群中的这些简单规则：</p>
<p>1、范围：蚂蚁观察到的范围是一个方格世界，蚂蚁有一个参数为速度半径（一般是3），那么它能观察到的范围就是3*3个方格世界，并且能移动的距离也在这个范围之内。</p>
<p>2、环境：蚂蚁所在的环境是一个虚拟的世界，其中有障碍物，有别的蚂蚁，还有外激素，外激素有两种，一种是找到食物的蚂蚁洒下的食物外激素，一种是找到窝的蚂蚁洒下的窝的外激素。每个蚂蚁都仅仅能感知它范围内的环境信息。环境以一定的速率让外激素消失。</p>
<p>3、觅食规则：在每只蚂蚁能感知的范围内寻找是否有食物，如果有就直接过去。否则看是否有外激素，并且比较在能感知的范围内哪一点的外激素最多，这样，它就朝外激素多的地方走，并且每只蚂蚁多会以小概率犯错误，从而并不是往外激素最多的点移动。蚂蚁找窝的规则和上面一样，只不过它对窝的外激素做出反应，而对食物外激素没反应。</p>
<p>4、移动规则： 每只蚂蚁都朝向外激素最多的方向移，并且，当周围没有外激素指引的时候，蚂蚁会按照自己原来运动的方向惯性的运动下去，并且，在运动的方向有一个随机的小的扰动。为了防止蚂蚁原地转圈，它会记住最近刚走过了哪些点，如果发现要走的下一点已经在最近走过了，它就会尽量避开。</p>
<p>5、避障规则：如果蚂蚁要移动的方向有障碍物挡住，它会随机的选择另一个方向，并且有外激素指引的话，它会按照觅食的规则行为。</p>
<p>7、播撒外激素规则：每只蚂蚁在刚找到食物或者窝的时候撒发的外激素最多，并随着它走远的距离，播撒的外激素越来越少。</p>
<p>根据这几条规则，蚂蚁之间并没有直接的关系，但是每只蚂蚁都和环境发生交互，而通过外激素这个纽带，实际上把各个蚂蚁之间关联起来了。比如，当一只蚂蚁找到了食物，它并没有直接告诉其它蚂蚁这儿有食物，而是向环境播撒外激素，当其它的蚂蚁经过它附近的时候，就会感觉到外激素的存在，进而根据外激素的指引找到了食物。成功的觅食算法正是最小化搜索食物的时间。</p>
<p><b>三 </b><b>蚁群算法的实现</b></p>
<p>理解蚁群算法的实质之后写出一个简单蚁群算法也不是太困难，关键是实现以上介绍的几个规则，下面用JAVA简单讲述一下以上规则的实现。</p>
<p>1、蚂蚁：蚂蚁是蚁群中最小的单位，是所以简单规则应用的最小个体。</p>
<p>&#160;</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code161'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157161"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p157code161"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> Ant
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span> Square SQUARE<span style="color: #008080;">;</span>           <span style="color: #666666;">//蚂蚁所在方格</span>
    <span style="color: #0000ff;">public</span> Food CARRYING <span style="color: #000080;">=</span> null<span style="color: #008080;">;</span>    <span style="color: #666666;">//所搬的食物数</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> ID<span style="color: #008080;">;</span>                  <span style="color: #666666;">//蚂蚁的编号</span>
    <span style="color: #0000ff;">public</span> boolean HELPING <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span> <span style="color: #666666;">//是否帮忙搬运食物</span>
&nbsp;
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> move<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> turn<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">//蚂蚁移动到下一个方格</span>
<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>2、范围：蚂蚁所在的方格应该包含附近的方格编号，所含食物数量，蚂蚁数量，外激素的浓度，以及坐标等信息。</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code162'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157162"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code" id="p157code162"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> Square
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">public</span> Square NE<span style="color: #008080;">;</span>            <span style="color: #666666;">//附近的8个方向的方格</span>
&nbsp;
     <span style="color: #0000ff;">public</span> Square N<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square NW<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square W<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square SW<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square S<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square SE<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> Square E<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">public</span> LinkedList ANTS<span style="color: #008080;">;</span>        <span style="color: #666666;">//本方格中包含的蚂蚁</span>
     <span style="color: #0000ff;">public</span> Food FOOD<span style="color: #008080;">;</span>            <span style="color: #666666;">//本方格中包含的食物数</span>
     <span style="color: #0000ff;">public</span> Nest NEST<span style="color: #008080;">;</span>                <span style="color: #666666;">//方格为蚁穴</span>
     <span style="color: #0000ff;">public</span> Pheromone_1 PHEROMONE_1<span style="color: #008080;">;</span>            <span style="color: #666666;">//本方格中的外激素含量</span>
     <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> X<span style="color: #008080;">;</span>            <span style="color: #666666;">//本方格的坐标</span>
     <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> Y<span style="color: #008080;">;</span>
     <span style="color: #0000ff;">private</span> World WORLD<span style="color: #008080;">;</span>            <span style="color: #666666;">//所属的环境</span>
     <span style="color: #0000ff;">public</span> boolean WALL<span style="color: #008080;">;</span>            <span style="color: #666666;">//是否有障碍物</span>
&nbsp;
    <span style="color: #0000ff;">public</span> Square<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> x, <span style="color: #0000ff;">int</span> y, World world<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        FOOD <span style="color: #000080;">=</span> null<span style="color: #008080;">;</span>
        NEST <span style="color: #000080;">=</span> null<span style="color: #008080;">;</span>
        PHEROMONE_1 <span style="color: #000080;">=</span> null<span style="color: #008080;">;</span>
        X <span style="color: #000080;">=</span> x<span style="color: #008080;">;</span>
        Y <span style="color: #000080;">=</span> y<span style="color: #008080;">;</span>
        WORLD <span style="color: #000080;">=</span> world<span style="color: #008080;">;</span>
        WALL <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
        ANTS <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> LinkedList<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>3、环境：环境是由多个方格组成的，是一个平面的，因此用一个方格的二维数组来表示是最合适不过的。</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code163'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157163"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p157code163"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> World
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">private</span> Square<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> WORLD<span style="color: #008080;">;</span>        <span style="color: #666666;">//定义环境二维数组</span>
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">int</span> WIDTH<span style="color: #008080;">;</span>                <span style="color: #666666;">//环境的长宽</span>
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">int</span> HEIGHT<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">private</span> Pheromone_1List P1LIST<span style="color: #008080;">;</span>        <span style="color: #666666;">//保存所有外激素的列表</span>
&nbsp;
    <span style="color: #0000ff;">public</span> World<span style="color: #008000;">&#40;</span>Pheromone_1List p1list<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">this</span>.<span style="color: #007788;">WIDTH</span> <span style="color: #000080;">=</span> Settings.<span style="color: #007788;">WIDTH</span><span style="color: #008080;">;</span>
        <span style="color: #0000dd;">this</span>.<span style="color: #007788;">HEIGHT</span> <span style="color: #000080;">=</span> Settings.<span style="color: #007788;">HEIGHT</span><span style="color: #008080;">;</span>
        <span style="color: #0000dd;">this</span>.<span style="color: #007788;">P1LIST</span> <span style="color: #000080;">=</span> p1list<span style="color: #008080;">;</span>
        WORLD <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> Square<span style="color: #008000;">&#91;</span>WIDTH<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>HEIGHT<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>&#160;&#160;&#160;&#160; 4、觅食规则，移动规则和避障规则：这三种规则全都跟蚂蚁的移动方向有关，并在移动前都要先计算周围方格的外激素浓度，选择外激素浓度最高的方格方向移动。</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code164'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157164"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code" id="p157code164"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">private</span> Square chooseBestSquare<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
     Square<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> square_list <span style="color: #000080;">=</span> <span style="color: #008000;">&#123;</span>SQUARE.<span style="color: #007788;">E</span>, SQUARE.<span style="color: #007788;">NE</span>, SQUARE.<span style="color: #007788;">N</span>, SQUARE.<span style="color: #007788;">NW</span>, SQUARE.<span style="color: #007788;">W</span>, SQUARE.<span style="color: #007788;">SW</span>, SQUARE.<span style="color: #007788;">S</span>, SQUARE.<span style="color: #007788;">SE</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">double</span> current_best_value <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">double</span> value <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
        Square square <span style="color: #000080;">=</span> SQUARE<span style="color: #008080;">;</span>
        <span style="color: #666666;">// 选择最好的方格</span>
&nbsp;
        <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>i<span style="color: #000080;">&lt;</span>square_list.<span style="color: #007788;">length</span><span style="color: #008080;">;</span>i<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            value <span style="color: #000080;">=</span> calculateSquareValue<span style="color: #008000;">&#40;</span>square_list<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><span style="color: #666666;">//计算方格值</span>
            <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>value <span style="color: #000080;">&gt;</span> current_best_value<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                current_best_value <span style="color: #000080;">=</span> value<span style="color: #008080;">;</span>
                square <span style="color: #000080;">=</span> square_list<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>square.<span style="color: #007788;">ANTS</span>.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&gt;=</span> Settings.<span style="color: #007788;">MAXIMUM_NUMBER_OF_ANTS</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
          <span style="color: #0000ff;">return</span> SQUARE<span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0000ff;">return</span> square<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code165'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157165"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p157code165"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">double</span> calculateSquareValue<span style="color: #008000;">&#40;</span>Square s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">double</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> thresholds <span style="color: #000080;">=</span> Settings.<span style="color: #007788;">THRESHOLDS</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>s<span style="color: #000080;">==</span>null <span style="color: #000040;">||</span> s.<span style="color: #007788;">WALL</span><span style="color: #008000;">&#41;</span> <span style="color: #666666;">// 方格有障碍物</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">100000</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// 计算方格中各项参数的值</span>
    <span style="color: #0000ff;">return</span> s.<span style="color: #007788;">getFood</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">*</span>thresholds<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span>        <span style="color: #666666;">// 食物</span>
    <span style="color: #000040;">+</span> s.<span style="color: #007788;">getPheromone_1</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">*</span> thresholds<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span>    <span style="color: #666666;">// 外激素</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>5、播撒外激素规则：每只蚂蚁找到食物后会根据食物的数量播撒相应量的外激素，以便其它蚂蚁能够更快得找到这堆食物。</p>
<p>
<div class="wp_codebox_msgheader"><span class="right"></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p157code166'); return false;">View Code</a> CPP</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p157166"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p157code166"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> putPheromone_1<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> amount<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>SQUARE.<span style="color: #007788;">getPheromone_1</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;</span> Settings.<span style="color: #007788;">PHEROMONE_LIMIT</span><span style="color: #008000;">&#41;</span>
     SQUARE.<span style="color: #007788;">addPheromone_1</span><span style="color: #008000;">&#40;</span>amount<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

</p>
<p>从以上蚁群算法中各个要素的代码来看，实现蚁群算法并不难。每只蚂蚁并不是像我们想象的需要知道整个环境的信息，它们只关心很小范围内的眼前信息，而且根据这些局部信息利用几条简单的规则进行决策，这样，在蚁群这个集体里，复杂性的行为就会凸现出来。这就是人工生命、复杂性科学解释的规律。</p>
<p><b>四 </b><b>蚁群算法的不足</b></p>
<p>本文实现的蚁群算法只是简单的大致模拟蚁群的觅食过程，真正的蚂蚁觅食过程远比这个复杂，比如增加蚂蚁搬运食物的距离和数量，蚂蚁在搬运食物发现更大的食物可能会丢弃原有食物，还可以增加蚂蚁搬运食物回蚁穴的最短路径的求解。同时需要注意的是，由于蚁群算法觅食的过程，蚁群算法可能会过早的收敛并陷入局部最优解。</p>
]]></content:encoded>
			<wfw:commentRss>http://zhuwenhao.com/157/%e6%8a%80%e6%9c%af/%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%e8%af%ad%e8%a8%80/cpp-%e8%af%ad%e8%a8%80/%e8%bd%ac%e8%bd%bd%e7%ae%80%e5%8d%95%e8%9a%81%e7%be%a4%e7%ae%97%e6%b3%95%e7%9a%84%e5%ae%9e%e7%8e%b0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

