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
逻辑与算术
119
6.6.4
 参考
6.7
6.8
14.12
A.9
6.7
 用模式匹配进行测试
6.7.1
 问题
你不想对字符串进行字面匹配,而是想看看它是否符合某种模式。例如,想知道是否存在
JPEG
类型的文件。
6.7.2
 解决方案
if
语句中使用复合命令
[[ ]]
,以便在等量运算符右侧启用
shell
风格的模式匹配:
if
[[ "${MYFILENAME}" == *.jpg ]]
6.7.3
 讨论
[[ ]]
语法不同于
test
命令的老形式
[
,它是一种较新的
bash
机制(
2.01
版左右才出现)。
能够在
[ ]
中使用的运算符也可用于
[[ ]]
,但在后者中,等号是一种更为强大的字符串
比较运算符。就像我们一样,你也可以使用
=
==
,两者在语义上相同。我们偏好
==
(尤
其是进行模式匹配时),这样更加醒目,但模式匹配功能可不是因此而有的,它源于复合
命令
[[ ]]
标准模式匹配包括
*
(匹配任意数量的字符)、
?
(匹配单个字符)以及
[ ]
(匹配字符列表
中的任意一个)。注意,其写法类似于
shell
文件通配符,但和正则表达式可不是一回事。
如果进行模式匹配,就别把模式放入引号。否则,就只能匹配到以星号为首的字符串
4
通过启用某些
bash
选项,可以使用一些更为强大的模式匹配功能。我们来扩展一下之前的
例子,要求其查找以
.jpg
.jpeg
结尾的文件名。可以这么做:
shopt -s extglob
if
[[ "$FN" == *.@(jpg|jpeg) ]]
then
# ...
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