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版)
执行命令
71
将其作为提供给
exit()
函数的参数值,例如,
exit(4);
会返回
4
。对于
shell
而言,退出
0
代表成功,非
0
则代表失败。
如果正在编写
bash
脚本,那么要确保明确设置了返回值,以便
$?
得以正确设置。如果不
这样做,
$?
的值则是最后执行的那个命令的返回值,但这未必是你想要的结果。
4.5.4
 参考
4.4
4.6
4.6
 减少
if
语句的数量
4.6.1
 问题
作为一名尽职尽责的程序员,你牢记着上节所讲的内容。你将相关的概念应用于最近编写
shell
脚本,却发现其中充斥着检查各个命令返回值的
if
语句,导致脚本难以阅读。有
没有什么别的办法呢?
4.6.2
 解决方案
bash
中使用
&&
运算符,根据条件执行命令。
cd mytmp && rm *
4.6.3
 讨论
&&
分隔两个命令,以此告诉
bash
先执行第一个命令,如果该命令成功(退出状态为
0
),再执行第二个命令。这非常类似于用
if
语句检查第一个命令的退出状态,从而判断
是否执行第二个命令。
cd mytmp
if
(( $? == 0 ));
then
rm * ;
fi
&&
语法会让人想起
C
语言中的逻辑
AND
运算符。如果了解逻辑运算(以及
C
语言),那么
你应该记得在评估逻辑表达式
A AND B
时,如果(子)表达式
A
和(子)表达式
B
均为真,
则整个表达式才为真。如果其中任何一个为假,则整个表达式为假。
C
语言利用了这个事
实,当编写
if (A && B) { ... }
之类的表达式时,它会先评估表达式
A
。如果为假,那么
它甚至都不会再费事去评估 ...
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