Skip to Content
bash shell脚本编程经典实例 (第2版)
book

bash shell脚本编程经典实例 (第2版)

by Carl Albing, JP Vossen
January 2021
Intermediate to advanced
581 pages
15h 7m
Chinese
Posts & Telecom Press
Content preview from bash shell脚本编程经典实例 (第2版)
107
6
shell
逻辑与算术
相较于最初的
Bourne shell
,现代
bash
版本的最大改进之一体现在算术方面。早期的
shell
版本没有内建的算术功能,哪怕是给变量加
1
,也得调用单独的程序来完成。尽管算术
机制如此不堪,但很多任务中仍旧少不了
shell
的身影,从某种程度上来说,这也反衬出
shell
以往的强大功用(现在依然如此)。过了一段时间以后,我们明显发现要有一种直观
的语法,用以实现自动化重复性任务所需要的简单计数功能。正是早期
Bourne shell
在此
项上的缺失成就了
csh
,当时后者在
shell
编程中引入了类似于
C
语言的语法,其中就包括
数字类型变量。好吧,过去是过去,现在是现在。如果有一阵子没了解过
bash shell
的算
术功能,如今你会感到非常惊讶。
除了算术,还有程序员都很熟悉的控制结构。有用于条件判断的
if/then/else
结构,以及
while
循环和
for
循环,你也会在其中发现一些
bash
的奇特之处。
case
语句的字符串模式
匹配能力令其具备了异常强大的功能,另外,
select
用起来也挺古怪。讨论过这些特性之
后,我们将利用它们构建两个简单的命令行计算器,以此为本章作结。
6.1
 在
shell
脚本中执行算术操作
6.1.1
 问题
你需要在
shell
脚本中执行一些简单的算术操作。
6.1.2
 解决方案
$(( ))
let
进行整数运算。例如:
COUNT=$((COUNT + 5 + MAX * 2))
let COUNT+='5+MAX*2'
108
6
6.1.3
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

bash 网络安全运维

bash 网络安全运维

Paul Troncone, Carl Albing
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9787115553782