zoukankan      html  css  js  c++  java
  • [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
    
  • 相关阅读:
    python re模块
    python
    python
    Django学习手册
    Django学习手册
    前端
    前端
    Django学习手册
    前端
    Database学习
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14398199.html
Copyright © 2011-2022 走看看