How to convert a string from uppercase to lowercase in Bash?

This question already has an answer here:

  • How to convert a string to lower case in Bash? 18 answers

  • If you are using bash 4 you can use the following approach:

    x="HELLO"
    echo $x  # HELLO
    
    y=${x,,}
    echo $y  # hello
    
    z=${y^^}
    echo $z  # HELLO
    

    Use only one , or ^ to make the first letter lowercase or uppercase .


    The correct way to implement your code is

    y="HELLO"
    val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
    string="$val world"
    

    This uses $(...) notation to capture the output of the command in a variable. Note also the quotation marks around the string variable -- you need them there to indicate that $val and world are a single thing to be assigned to string .

    If you have bash 4.0 or higher, a more efficient & elegant way to do it is to use bash builtin string manipulation:

    y="HELLO"
    string="${y,,} world"
    

    Why not execute in backticks ?

     x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 
    

    This assigns the result of the command in backticks to the variable x . (ie it's not particular to tr but is a common pattern/solution for shell scripting)

    You can use $(..) instead of the backticks. See here for more info.

    链接地址: http://www.djcxy.com/p/57128.html

    上一篇: 在单引号内双引号内退出单引号

    下一篇: 如何在Bash中将字符串从大写转换为小写?