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

前端 未结 15 2169
离开以前
离开以前 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:56

    I believe this is what you're looking for

    magic() { # returns unexpanded tilde express on invalid user
        local _safe_path; printf -v _safe_path "%q" "$1"
        eval "ln -sf ${_safe_path#\\} /tmp/realpath.$$"
        readlink /tmp/realpath.$$
        rm -f /tmp/realpath.$$
    }
    

    Example usage:

    $ magic ~nobody/would/look/here
    /var/empty/would/look/here
    
    $ magic ~invalid/this/will/not/expand
    ~invalid/this/will/not/expand
    

提交回复
热议问题