How to convert a string to lower case in Bash?

前端 未结 20 2044
慢半拍i
慢半拍i 2020-11-22 09:40

Is there a way in bash to convert a string into a lower case string?

For example, if I have:

a=\"Hi all\"

I want to convert it to:<

20条回答
  •  长发绾君心
    2020-11-22 09:53

    If using v4, this is baked-in. If not, here is a simple, widely applicable solution. Other answers (and comments) on this thread were quite helpful in creating the code below.

    # Like echo, but converts to lowercase
    echolcase () {
        tr [:upper:] [:lower:] <<< "${*}"
    }
    
    # Takes one arg by reference (var name) and makes it lowercase
    lcase () { 
        eval "${1}"=\'$(echo ${!1//\'/"'\''"} | tr [:upper:] [:lower:] )\'
    }
    

    Notes:

    • Doing: a="Hi All" and then: lcase a will do the same thing as: a=$( echolcase "Hi All" )
    • In the lcase function, using ${!1//\'/"'\''"} instead of ${!1} allows this to work even when the string has quotes.

提交回复
热议问题