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版)
102
5
5.20
 用
bash
实现
basename
5.20.1
 问题
basename
命令可以做到你想要的,但是能够在不调用外部命令的情况下得到相同的结果
吗?
bash
的字符串操作能不能做到?
5.20.2
 解决方案
是的,
bash
能够从
shell
变量中剥离路径中的目录,只留下最后一部分(文件名)。当你想
按以下方式写时:
FILE=
$(
basename $FULLPATHTOFILE
)
其实只需要写成:
FILE=${FULLPATHTOFILE##*/}
5.20.3
 讨论
这两种写法的不同之处在于花括号。第一种写法使用的是括号(旧式写法是
``
),它会生
成一个子
shell
来执行参数值为
$FULLPATHTOFILE
的命令
basename
。第二种写法使用的花括
号只是
shell
变量替换语法的一部分,并不会生成子
shell
,也不会执行命令。它从字符串
起始位置开始(因为
#
)查找并删除匹配模式
*/
的最长子串(因为
##
)。
*
匹配任意数量
的字符,
/
仅代表其字面含义。对于路径
/usr/local/bin/mycmd
,指定模式会匹配(并删
除)
/usr/local/bin/
,将剩下的
mycmd
赋给变量
$FILE
因为
basename
命令会忽略路径结尾的
/
,所以
$(basename /usr/local/bin/)
会返回
bin
,而我们用
bash
所实现的版本则返回空串(因为模式
*/
所能匹
配的最长内容就是整个字符串)。为了与
basename
兼容,第一件事就是删除
路径结尾的
/
真正的
basename
命令还可以将要删除的后缀作为第二个可接受的参数。 ...
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