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
变量
103
5.21
 用
bash
实现
dirname
5.21.1
 问题
dirname
命令的作用和你预想的一样,但就像
basename
,它也是一个单独的可执行文件,
需要在子
shell
中运行。能不能用字符串操作来代替?
5.21.2
 解决方案
当然能。用字符串操作删除文件名(路径中的最后一部分),尽可能多地保留路径中的目
录部分。
DIR=${MYPATHTOFILE%/*}
5.21.3
 讨论
如果变量中保存的是
/usr/local/bin/mycmd
,我们希望得到的是
/usr/local/bin
,同时丢
弃最后一部分(文件名)。由于路径中的各个部分是由斜线分隔的,从右侧开始(因为
%
删除匹配模式“斜线之后跟着任意数量字符(
/*
)”的最短子串(因为只有一个
%
,而不是
两个)即可。
这个示例演示了如何对
shell
变量进行字符串操作。其中并未给出完整的、
可兼容的
dirname
命令替代方案,尤其是针对一些路径名以斜线结尾的边缘
情况。
5.21.4
 参考
man dirname
,参见其他选项以及细微的差异
5.18
5.20
5-1
5.22
 选取
CSV
的替换值
5.22.1
 问题
你想制作一个由逗号分隔的值列表,但不希望开头或结尾处出现逗号。
5.22.2
 解决方案
如果在循环内部用
LIST="${LIST},${NEWVAL}"
构建该列表,那么第一次循环(此时
LIST
空)过后会得到一个前导逗号。你可以对
LIST
进行特殊的初始化处理,以便它在进入循环
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