编程小贴士

给你的编程提供小点子


BASH脚本学习教程

在这一节中我将学习一些简单的脚本,它将有利于你深入学习一些知识。
一个最经典的Hello World程序
#!/bin/bash
echo Hello World

这 个脚本只有二行,它的第一行这个脚本程序由那个程序来解释.第二行只有一个简单的动作,它的功能是在终端上打印出一行”Hello World” 。如果你测试着执行这个命令时(./hello.sh),你将会得到一个command not found的信息,这种情况大部分可能是你的第一行#!/bin/bash这个程序有问题,你一定要确保bash可以找到并且可用。(一般情况下你还要对 这个脚本附一个可执行权限)
#chmod u+x hello.sh
一个非常简单的备份脚本
#!/bin/bash
tar -cZf /var/my-backup.tgz /home/me/

在这个脚本中,它替换了上一个例子的将一行信息打印在终端上的功能,取尔代之的是一个备份/home目录的tar备份命令。
关于重定向的一些信息
最基本的理论基础
这里有对于三个文件的重定向定义: stdin(标准输入), stdout(标准输出) and stderr(标准错误输出) (std=standard).
基本上你可以
1. 重定向 stdout 到一个文件
2. 重定向 stderr 到一个文件
3. 重定向 stdout 到stderr
4. 重定向 stderr 到 stdout
5. 重定向 stderr 到 stdout 中并且成为一个文件
6. 重定向 stderr and stdout to stdout
7. 重定向 stderr and stdout to stderr
在Linux中 1代表 ‘标准输出’, 2代表’标准错误’
标准输出
这个例子将会使ls的显示结果重定向到一个文件中.
ls -l > ls-l.txt

标准错误
这个例子将会使grep命令在运行过程中出现的错误输出到一个文件中
grep da * 2> grep-errors.txt

管道
这一节我们将解释一个非常简单的并且你以后一定会用到的功能,它就是管道。
为什么大家都会用到管道?
管道可以使你非常方便的将一个程序的结果转向到另外一个程序中。
一个sed的例子
这个例子使用了非常简单的管道功能:
ls -l | sed -e “s/[aeio]/u/g”

当我们执行以下命令后:首先ls –l会先执行并且它会输出结果信息但是如果它的后面跟是一个管道符的话,那么它就会将结果重新定向到sed这个程序中,sed使用了替换功能,所以这个例子执行完会,会将ls –l结果中所有含有aeio的英文单词替换成单词u.
通过另外的方法实现ls –l *.txt
也许这种方法不同于ls –l *.txt,但是它避免了出现一条 No Such file Or Directory这种信息。
ls -l | grep “.txt”

当ls –l 执行后,它会将程序结果输出到grep这个程序中,并且去匹配.txt这条信息。
变量
你可在任何编程语言中使用变量,但是在脚本编程中它们是没有类型的,简称弱类型编程语言,在这个变量中可以保含一个数字,一个字符串,一个单词等。你并不需要声明这个变量,它会在引用这个变量时创建它。
使用变量来实现一个简单的Hello World
#!/bin/bash
STR=”Hello World!”
echo $STR

第二行建立一个STR的变量并且为其附了一个“Hello World”的字符串变量值。当在这个变量前面加上一个$符号时,我们就将会得到这个变量的值。
例子(一个使用变量的备份脚本)
#!/bin/bash
OF=/var/my-backup-$(date +%Y%m%d).tgz
tar -cZf $OF /home/me/

局部变量
局部变量的生命是有限的,请看下面的例子
#!/bin/bash
HELLO=Hello
function hello {
local HELLO=World
echo $HELLO
}
echo $HELLO
hello
echo $HELLO

条件语句
条件语句可以使你决定是完成一个运作或是不去完成一个动作时,通过一些判断来实现,一般情况都是通过一些操作符来实现判断。
条件语句可以有许多实现方法,最多的情况是基于if expression then 这种情况,也就是大家常常说的if判断语句。它的语法基本结构如下:
if [expression];
then
code if ‘expression’ is true.
fi
一个最基本的使用if …then的例子
#!/bin/bash
if [ “foo” = “foo” ]; then
echo expression evaluated as true
fi

这段代码执行if判断,如果foo等于foo的话,那么你就会执行then语句下的输出语句,最后通过fi来结束,这里我要强调一点,就是很多新手在输入源码时特别是在if 语句后面没有空格,在大括号后面没有空格,在等号两边没有空格,这些都会制造出一些麻烦的。
一个简单的控制if .. then …else
#!/bin/bash
if [ “foo” = “foo” ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

6.4 通过变量进行判断控制
#!/bin/bash
T1=”foo”
T2=”bar”
if [ “$T1″ = “$T2″ ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi

7. 循环结构
在这一节中,你将会学习for、while、until loops循环
对于for 循环它有一点不同于其他的编程语言,它有一点像VB中的for each语句,就是所谓的递归的循环。
对于while循环,它其实是一个加强的if语句,如果它的条件为真,那么它就一直执行while循环中的语句中的内容。
7.1 For sample
#!/bin/bash
for i in $( ls ); do
echo item: $i
done

在第二行上,我们声明了一个i的变量,它将一直将ls命令的结果全部循环出来。其中do 和done之间是所要执行的代码。
While循环例子
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
这里面大家可能看到一个-lt的命令选项,这里它代表小于等于
-eq 等于
-ne 不等于
-gt 大于
-ge 大于等于
-lt 小于
-le 小于等于
Until的例子
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done

函数
对于大多数编程语言,你都可以调用函数来执行一段代码,这样可以使用减少重复的书写代码。
函数的例子
#!/bin/bash
function quit {
exit
}
function hello {
echo Hello!
}
hello
quit
echo foo

在 2-4行包含了一个quit函数,在5-7行包含了 hello函数,如果你不是很确定这个脚本是是什么意思,那么我建议试试它。Notice that a functions don’t need to be declared in any specific order.
当你运行这个脚本时你的程序将会最先调用hello函数,以后再调用quit函数最后才执行echo 输出命令。
在函数中使用参数
#!/bin/bash
function quit {
exit
}
function e {
echo $1
}
e Hello
e World
quit
echo foo

这个脚本几乎和前一个脚本没有什么不能,但最主要的不同是e这个函数可以使用参数了。
用户接口
使用select命令制作简单的菜单
#!/bin/bash
OPTIONS=”Hello Quit”
select opt in $OPTIONS; do
if [ “$opt” = “Quit” ]; then
echo done
exit
elif [ “$opt” = “Hello” ]; then
echo Hello World
else
clear
echo bad option
fi
done

如果你运行这个脚本你将会看到一个非常简单的菜单
使用read读入用户输入
在多数情况下你可能会用到提示请进行输入这种状态并且有几种方法可以用。这是其中的一种方法:
#!/bin/bash
echo Please, enter your name
read NAME
echo “Hi $NAME!”

对于变量来说,你可以通过多个值来读入。
#!/bin/bash
echo Please, enter your firstname and lastname
read FN LN
echo “Hi! $LN, $FN !”

算术操作
使用以下的命令:
echo 1 + 1
如果你希望看到2,那么你会很失望,那么我们应该如何进行操作哪? echo $((1+1))
我们可以使用以下方法:
echo $[1+1]

算术操作
+

*
/
% (remainder)
关系操作
-lt (<)
-gt (>)
-le (<=)
-ge (>=)
-eq (==)
-ne (!=)

180 Responses to “ BASH脚本学习教程 ”

  1. best pron说道:

    MEZOyB Keep in the excellent function, I read few articles on this website along with I conceive your web blog is incredibly interesting and contains got companies of fantastic info.

  2. me suba说道:

    Ri3WGN I will right away grab your rss feed as I can at in finding your e-mail subscription hyperlink or newsletter service. Do you ave any? Kindly allow me know in order that I may subscribe. Thanks.

  3. Very good blog post.Really looking forward to read more.

  4. painting说道:

    Say, you got a nice article post.Much thanks again. Want more.

  5. Smokers Lungs说道:

    Im thankful for the blog post.Thanks Again. Cool.

  6. Looking forward to reading more. Great article.Really thank you! Want more.

  7. This is one awesome article post. Fantastic.

  8. This information is worth everyone as attention. When can I find out more?

  9. I think this is a real great blog.Thanks Again. Great.

  10. or even I achievement you get right of entry to constantly quickly.

  11. Oluwadamilare说道:

    Very good blog article.Really thank you! Want more.

  12. Really informative blog article.Thanks Again. Fantastic.

  13. You made some first rate points there. I looked on the internet for the issue and found most people will go together with along with your website.

  14. I think, that you commit an error. Let as discuss it.

  15. buy说道:

    There is clearly a bundle to identify about this. I suppose you made certain nice points in features also.

  16. W88说道:

    There is definately a great deal to know about this issue. I really like all the points you have made.

  17. Is there any way you can remove people from that service?

  18. Wow! This can be one particular of the most useful blogs We ave ever arrive across on this subject. Actually Great. I am also an expert in this topic therefore I can understand your effort.

  19. Thanks for the blog.Thanks Again. Much obliged.

  20. This excellent website really has all of the info I needed about this subject and didn at know who to ask.

  21. pre booked说道:

    Remarkable issues here. I am very glad to peer your post. Thank you a lot and I am looking forward to touch you. Will you kindly drop me a mail?

  22. Im thankful for the blog post.Much thanks again. Fantastic.

  23. I was more than happy to uncover this website. I want to to thank you for your time due to this wonderful

  24. Way cool! Some very valid points! I appreciate you penning this write-up and the rest of the site is extremely good.

  25. status说道:

    Wow, amazing weblog format! How long have you ever been running a blog for? you made running a blog glance easy. The full glance of your site is fantastic, let alone the content!

  26. Loving the information on this internet site, you have done great job on the articles.

  27. Im thankful for the post.Really thank you! Great.

  28. PhD Green Card说道:

    Very neat article.Really thank you! Really Cool.

  29. share now说道:

    Thank you ever so for you article post.Really thank you! Want more.

  30. du an Rio Verde说道:

    Thanks-a-mundo for the article.Really looking forward to read more.

  31. Discover More说道:

    There is apparently a lot to identify about this. I believe you made certain good points in features also.

  32. Nwokolo说道:

    Im thankful for the article.Really looking forward to read more. Really Great.

  33. san pham noel说道:

    your placement in google and could damage your high-quality score if advertising and marketing with Adwords.

  34. klm voucher说道:

    vibram five fingers shoes WALSH | ENDORA

  35. This very blog is really awesome additionally diverting. I have picked up many useful stuff out of it. I ad love to come back every once in a while. Cheers!

  36. Some truly good posts on this website , thankyou for contribution.

  37. Really enjoyed this blog article.Thanks Again. Really Cool.

  38. P. Diddy说道:

    Thanks for the article.Thanks Again. Much obliged.

  39. This particular blog is without a doubt educating additionally diverting. I have picked a bunch of interesting advices out of this amazing blog. I ad love to visit it again soon. Thanks!

  40. Chong tham说道:

    Thanks for the blog.Really looking forward to read more. Really Great.

  41. Warehousing Kiev说道:

    papers but now as I am a user of net so from now I am

  42. wonderful issues altogether, you simply received a logo new reader. What would you suggest about your post that you made a few days ago? Any sure?

  43. tieng nhat说道:

    Major thankies for the blog.Thanks Again. Really Great.

  44. Im thankful for the blog.Thanks Again. Really Great.

  45. I really liked your article.Thanks Again. Awesome.

  46. isabel marant sneakers pas cher isabel marant sneakers pas cher

  47. Really superb information can be found on site.

  48. online loans说道:

    Im grateful for the article.Really thank you! Keep writing.

  49. Giay nam说道:

    Im obliged for the blog post.Really looking forward to read more. Fantastic.

  50. It is laborious to search out knowledgeable people on this matter, but you sound like you recognize what you are speaking about! Thanks

  51. Your style is very unique in comparison to other people I have read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just bookmark this site.

  52. Stunning story there. What occurred after? Good luck!

  53. This is one awesome article post.Much thanks again. Want more.

  54. Thank you ever so for you article.Really thank you! Really Cool.

  55. useful说道:

    Simply wanna remark that you have a very decent site, I the design it really stands out.

  56. womensfit说道:

    wonderful issues altogether, you simply gained a logo new reader. What might you suggest in regards to your post that you just made some days in the past? Any certain?

  57. You have brought up a very great points, thanks for the post.

  58. Signes astrologique ascendant comment trouver son ascendant astrologique

  59. Your posts customarily consist of a correct amount of truly up to date information. Everyplace accomplish you extend up with this? Emphatically declaring you are fantastically creative. Thanks again

  60. discount code说道:

    There as definately a lot to learn about this issue. I love all the points you have made.

  61. your weblog posts. Any way I will be subscribing for your feeds

  62. There is certainly a great deal to find out about this issue. I love all of the points you made.

  63. Como tejer说道:

    with the turn out of this world. The second level is beyond the first one

  64. Souls in the Waves Great Morning, I just stopped in to go to your web site and thought I ad say I liked myself.

  65. local说道:

    This is one awesome article post.Really looking forward to read more. Cool.

  66. worth说道:

    methods with others, why not shoot mee an email if interested.

  67. This blog is definitely awesome as well as factual. I have picked up helluva handy advices out of this blog. I ad love to go back again and again. Thanks a bunch!

  68. You in fact dealt with several engaging items in this post. I came across it by employing Bing and IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžve got to admit that I am now subscribed to your site, it really is very decent (:

  69. School news说道:

    Major thanks for the blog article.Really looking forward to read more. Will read on

  70. Waec exam说道:

    Super-Duper site! I am loving it!! Will come back again. I am bookmarking your feeds also

  71. you can do with a few pics to drive the message home a little bit, but other than that, this is fantastic blog.

  72. time as looking for a similar topic, your website came up, it seems good.

  73. click here说道:

    your blog? Its very well written; I love what youve got

  74. You made some decent points there. I looked on the internet for the issue and found most people will approve with your blog.

  75. Major thankies for the blog article.Thanks Again.

  76. the time to study or go to the content material or web-sites we have linked to below the

  77. Moskito说道:

    There is perceptibly a bunch to identify about this. I believe you made some good points in features also.

  78. tm objection说道:

    Major thanks for the post.Really thank you! Awesome.

  79. Its such as you learn my mind! You seem to grasp so much

  80. Nice blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  81. Im obliged for the blog.Thanks Again. Really Great.

  82. Thank you, I have just been looking for info about this subject for ages and yours is the best I have discovered so far. But, what about the bottom line? Are you sure about the source?

  83. Wonderful post! We are linking to this great content on our site. Keep up the good writing.

  84. Very fantastic info can be found on website.

  85. tips说道:

    Thanks-a-mundo for the article.Really thank you!

  86. Judi Tembak Ikan说道:

    This is a topic that as close to my heart Cheers! Exactly where are your contact details though?

  87. travellers说道:

    If you are going for best contents like me, only pay a quick visit this website every day as it offers quality contents, thanks

  88. in his/her brain that how a user can be aware of it.

  89. for more info说道:

    This unique blog is really interesting and besides diverting. I have found helluva handy advices out of it. I ad love to come back over and over again. Thanks!

  90. this is wonderful blog. A great read. I all certainly be back.

  91. not positioning this submit higher! Come on over and talk over with my website.

  92. This is one awesome post.Really looking forward to read more. Want more.

  93. Thanks-a-mundo for the blog post.Really looking forward to read more. Want more.

  94. go to see说道:

    I think this internet site has got some really fantastic info for everyone . аЂа‹аЂ Nothing great was ever achieved without enthusiasm.аЂ аЂа› by Ralph Waldo Emerson.

  95. I saw plenty of website but I conceive this one contains a thing special in it. The finest effect regarding fine people is experienced after we ave got left their presence. by Rob Waldo Emerson.

  96. lawyer说道:

    in the same niche. Your blog provided us beneficial information to work on.

  97. Really appreciate you sharing this article post.Really thank you! Great.

  98. receive four emails with the same comment.

  99. mjagkie okna说道:

    There as certainly a great deal to find out about this topic. I like all the points you have made.

  100. It as difficult to find well-informed people on this subject, but you sound like you know what you are talking about! Thanks

  101. Chapel说道:

    Wow, great article post.Much thanks again. Cool.

  102. official site说道:

    It as not that I want to copy your web-site, but I really like the design and style. Could you let me know which theme are you using? Or was it custom made?

  103. visit说道:

    Very good article post.Much thanks again. Cool.

  104. free guest post说道:

    This site really has all of the information I needed about this subject and didn at know who to ask.

  105. more info说道:

    Outstanding work over again! Thumbs up=)

  106. click here说道:

    You have noted very interesting points ! ps nice web site. I understand a fury in your words, But not the words. by William Shakespeare.

  107. This blog was how do you say it? Relevant!! Finally I have found something that helped me. Many thanks!

  108. Major thanks for the blog article.Thanks Again. Want more. this link

  109. I really liked your blog article.Really thank you!

  110. Some really good content on this web site , thankyou for contribution.

  111. share说道:

    pretty useful material, overall I think this is worthy of a bookmark, thanks

  112. Okey说道:

    This web site certainly has all of the info I wanted about this subject and didn at know who to ask.

  113. Very good write-up. I definitely appreciate this website. Continue the good work!

  114. Wow! This can be one particular of the most beneficial blogs We ave ever arrive across on this subject. Basically Great. I am also an expert in this topic therefore I can understand your hard work.

  115. There is apparently a bundle to know about this. I consider you made some nice points in features also.

  116. announce online说道:

    Thanks for sharing, this is a fantastic article.Really thank you! Really Cool.

  117. just go to说道:

    Some genuinely choice blog posts on this website , bookmarked.

  118. Very informative post.Really thank you! Keep writing.

  119. It is a beautiful picture with very good light-weight.

  120. link说道:

    I was recommended this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are wonderful! Thanks!

  121. You have brought up a very superb details , thankyou for the post.

  122. usually posts some extremely exciting stuff like this. If you are new to this site

  123. This is a topic which is near to my heart Thank you! Exactly where are your contact details though?

  124. cong ty luat说道:

    Some really select articles on this site, saved to fav.

  125. go there说道:

    I visited many blogs however the audio quality for audio songs current at this web page is in fact fabulous.

  126. You have made some good points there. I looked on the net for additional information about the issue and found most individuals will go along with your views on this web site.

  127. You have made some good points there. I checked on the internet for additional information about the issue and found most individuals will go along with your views on this web site.

  128. tampa seo说道:

    There is visibly a bunch to realize about this. I believe you made certain good points in features also.

  129. It as not that I want to duplicate your web page, but I really like the design and style. Could you let me know which style are you using? Or was it tailor made?

  130. genuine parts说道:

    Really enjoyed this article. Really Cool.

  131. click here说道:

    There is certainly a great deal to learn about this subject. I really like all of the points you ave made.

  132. I?d should verify with you here. Which is not something I often do! I take pleasure in reading a publish that may make individuals think. Also, thanks for allowing me to comment!

  133. Whats Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I hope to give a contribution & help other users like its aided me. Good job.

  134. Muchos Gracias for your post.Thanks Again. Cool.

  135. very nice publish, i certainly love this web site, carry on it

  136. Very nice style and superb articles, practically nothing else we need .

  137. You are not right. I am assured. I can prove it. Write to me in PM, we will talk.

  138. Looking forward to reading more. Great blog article.Really looking forward to read more. Awesome.

  139. Really informative article post.Really thank you! Great.

  140. You created various good points there. I did a search on the topic and discovered a lot of people will have the same opinion together with your weblog.

  141. Wow, great article.Really looking forward to read more. Great.

  142. Game Online说道:

    This blog is really cool and factual. I have found a bunch of interesting stuff out of this blog. I ad love to return again and again. Thanks a bunch!

  143. specialist on this space to resolve my problem. Maybe that is you!

  144. the plan of a user in his/her mind that how a user

  145. Really enjoyed this blog post. Fantastic.

  146. Wow, great article.Thanks Again. Fantastic.

  147. Your style is very unique in comparison to other people I have read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just book mark this web site.

  148. Really informative blog.Really thank you! Great.

  149. I truly appreciate this post.Really thank you! Cool.

  150. Major thanks for the article post.Much thanks again. Much obliged.

  151. Wow, great blog.Really thank you! Keep writing.

  152. Zebra说道:

    Spot on with this write-up, I truly suppose this website wants way more consideration. I all in all probability be again to learn much more, thanks for that info.

  153. Wow, amazing blog layout! How long have you ever been blogging for? you made blogging look easy. The full look of your website is magnificent, as well as the content material!

  154. techgearpage.com说道:

    Really enjoyed this post.Thanks Again. Want more.

  155. Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Wonderful. I am also a specialist in this topic so I can understand your effort.

  156. bitcoin说道:

    You obtained a really useful blog I ave been here reading for about an hour. I am a newbie as well as your achievement is really considerably an inspiration for me.

  157. read more说道:

    What as up to every body, it as my first visit of this blog; this blog carries awesome and truly fine information for visitors.

  158. ban ghe cafe说道:

    Major thankies for the post.Thanks Again. Really Cool.

  159. Thanks so much for the article post.Much thanks again. Want more.

  160. Nice Site , guys! Great Infos aswell. I bookmarked your site

  161. Very neat blog post.Much thanks again. Really Great.

  162. chinh nha说道:

    Thanks for sharing, this is a fantastic blog article.Really thank you! Keep writing.

  163. this topic for a long time and yours is the greatest I have

  164. This blog is really entertaining and factual. I have picked up helluva helpful things out of this source. I ad love to come back over and over again. Thanks!

  165. Your style is so unique compared to other people I have read stuff from. Many thanks for posting when you have the opportunity, Guess I all just bookmark this site.

  166. johns说道:

    This will be a great web site, might you be involved in doing an interview regarding how you developed it? If so e-mail me!

  167. suba me说道:

    9CxkTK It as really a nice and helpful piece of info. I am glad that you shared this useful information with us. Please keep us informed like this. Thanks for sharing.

  168. It as actually a great and useful piece of information. I am satisfied that you shared this useful tidbit with us. Please stay us informed like this. Thank you for sharing.

  169. mia pron khalifa说道:

    duITy3 It as best to participate in a contest for among the best blogs on the web. I all suggest this web site!

  170. I think this is a real great blog post.Much thanks again. Really Cool.

  171. Thanks for sharing, this is a fantastic blog post.Really thank you! Great.

  172. In my opinion you commit an error. I suggest it to discuss. Write to me in PM, we will talk.

  173. Woah! I am really digging the template/theme of this site. It as simple, yet effective.

  174. It as hard to come by experienced people for this topic, but you sound like you know what you are talking about! Thanks

  175. Really informative post.Really looking forward to read more. Great.

  176. Nice blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  177. official page说道:

    Im thankful for the blog article.Really thank you! Really Cool.

  178. That is a good tip particularly to those fresh to the blogosphere. Short but very accurate information Thanks for sharing this one. A must read post!

  179. post and a all round exciting blog (I also love the theme/design), I don at have time to look

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>