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版)
脚本编程基础:
shell
变量
77
这有什么关系?考虑一下,如果允许
=
两侧出现空白字符,那么变量赋值就会变成下面
这样:
MYVAR = something
看出来没有,此时
shell
很难区分出到底是要调用命令(如本例中的
ls
)还是要给变量赋
值。对于能够以
=
为参数的命令(如
test
)更是如此。所以,还是让事情简单点吧:变量
赋值时,
shell
不允许在
=
两侧出现空白字符。该规定的另一方面也值得注意:不要在文件
名中使用
=
,对于
shell
脚本尤为如此(尽管可行,但不推荐)。
其次需要注意的是,引用变量时要使用
$
符号。给变量赋值时不需要在变量名前加
$
,但
获取变量值时需要。(出现在表达式
$(( ))
中的变量是个例外。)用编译器的行话来说,赋
值和检索值在语法上的差异就是变量的左值(
L-value
)与右值(
R-value
)之间的差异(赋
值运算符的
左侧
右侧
)。
原因很简单,就是为了消除歧义。思考下列情况:
MYVAR=something
echo MYVAR is now MYVAR
正如这个示例试图指出的,你能分辨出哪个是字符串
MYVAR
,哪个是变量
MYVAR
吗?使用
引号?如果将字符串放进引号,那么一切只会更乱,你得将包括命令在内的所有非变量名
全部加上引号!没人想像下面这样敲命令:
"ls" "-l" "/usr/bin/xmms"
(对于那些想试试看的用户来说,没错,这么写确实也管用。)因此,不用将一切都加上引
号,使用右值语法来引用变量就够了。要想获得与某个变量名相关联的值,在变量名前加
$
符号即可。
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