[Bash] Set Default Arguments with Bash Shell Parameter Expansions
Shell Parameter Exapnsion
In this lesson, we'll see how shell parameter expansions can be used to simply expand a variable's valuable and also provide a default value to a variable, if not set. Note that there are many more possibilities with shell parameter expansions, so check bash's documentation to view them all.
It is same when you doing:
echo $USER
## or
echo ${USER}
${}
is called shell parameter expansion.
It is useful when you want to print as such:
echo $USER_$(date '+%Y')
Expected result was JOHN_2021
. But it just print John
.
That is because it doesn't know $USER_
.
To fix the issue, we can do:
${USER}_($date '+%Y')
Then we get the correct result.
Default value
echo ${str:-'default'}
It prints default
because $str
doesn't exist.
Example
Count files under dir:
nano count-files.sh
count-files.sh:
dir=${1:-$PWD} ## default to current dir
find "$dir" -type f -maxdepth 1 | wc -l
分类:
Tools
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-02-11 [HTML5] Add an SVG Image to a Webpage and Get a Reference to the Internal Elements in JavaScript
2019-02-11 [Angular] Angular i18n Alternative Expressions Support (select)
2019-02-11 [React + Functional Programming ADT] Create Redux Middleware to Dispatch Multiple Actions
2019-02-11 [React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
2019-02-11 [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
2019-02-11 [CSS3] Make a One-time CSS Animation that Does Not Revert to its Original Style
2017-02-11 [Ramda] Eliminate Function Arguments (Point-Free Style) with Ramda's Converge