微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐