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版)
94
5
5.12
6.15
13.1
13.2
5.13
 获取默认值
5.13.1
 问题
有一个可以接受命令行参数的
shell
脚本。你希望能够提供默认值,这样就不用每次都让用
户输入那些频繁用到的值了。
5.13.2
 解决方案
${:-}
语法引用参数并提供默认值。
FILEDIR=${1:-/tmp}
5.13.3
 讨论
在引用
shell
变量时,有多种特殊运算符可用。
:-
运算符的意思是,如果指定参数(这里
$1
)不存在或为空,则将运算符之后的内容(本例为
/tmp
)作为值。否则,使用已经设
置好的参数值。该运算符可用于任何
shell
变量,并不局限于位置参数(
$1
$2
$3
),
但后者是最常用到的。
当然,你也可以用更多的代码来实现:用
if
语句检查变量是否为空或不存在(我们将这
个作为练习留给你),但在
shell
脚本中,此类处理司空见惯,
:-
运算符可谓是一种颇受欢
迎的便捷写法。
5.13.4
 参考
bash
手册页中有关参数替换的部分
Cameron Newham
所著的
Learning the bash Shell, 3rd Edition
O
Reilly
出版),
91~92
Nelson H. F. Beebe
Arnold Robbins
合著的
Classic Shell Scripting
O
Reilly
出版),
113~114
5.14
5-1
5.14
 设置默认值
5.14.1
 问题
你的脚本依赖于某些常用(如
$USER
)或业务特定的环境变量。要想构建一个稳健的 ...
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