[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
posted @   Zhentiw  阅读(68)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示