[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 @ 2021-02-11 21:31  Zhentiw  阅读(67)  评论(0编辑  收藏  举报