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
    
  • 相关阅读:
    博客园侧边栏添加QQ链接
    通俗易懂的理解 Redux(知乎)
    Redux生态系统
    ReactNative环境搭建
    cordova插件开发
    java类初始化
    Cordova指令
    安卓中如何调用jni
    JNI开发的常见错误
    JNI-java native interface(java本地接口)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14398199.html
Copyright © 2011-2022 走看看