首页 > 系统服务 > 详细

[Bash] Set Default Arguments with Bash Shell Parameter Expansions

时间:2021-02-12 08:07:18      阅读:29      评论:0      收藏:0      [点我收藏+]

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

[Bash] Set Default Arguments with Bash Shell Parameter Expansions

原文:https://www.cnblogs.com/Answer1215/p/14398199.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!