How to manually expand a special variable (ex: ~ tilde) in bash

前端 未结 15 2313
离开以前
离开以前 2020-11-22 09:34

I have a variable in my bash script whose value is something like this:

~/a/b/c

Note that it is unexpanded tilde. When I do ls -lt on this

15条回答
  •  無奈伤痛
    2020-11-22 09:41

    Here's my solution:

    #!/bin/bash
    
    
    expandTilde()
    {
        local tilde_re='^(~[A-Za-z0-9_.-]*)(.*)'
        local path="$*"
        local pathSuffix=
    
        if [[ $path =~ $tilde_re ]]
        then
            # only use eval on the ~username portion !
            path=$(eval echo ${BASH_REMATCH[1]})
            pathSuffix=${BASH_REMATCH[2]}
        fi
    
        echo "${path}${pathSuffix}"
    }
    
    
    
    result=$(expandTilde "$1")
    
    echo "Result = $result"
    

提交回复
热议问题