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

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

    A safe way to use eval is "$(printf "~/%q" "$dangerous_path")". Note that is bash specific.

    #!/bin/bash
    
    relativepath=a/b/c
    eval homedir="$(printf "~/%q" "$relativepath")"
    echo $homedir # prints home path
    

    See this question for details

    Also, note that under zsh this would be as as simple as echo ${~dangerous_path}

提交回复
热议问题