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

前端 未结 15 2429
离开以前
离开以前 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 10:05

    Due to the nature of StackOverflow, I can't just make this answer unaccepted, but in the intervening 5 years since I posted this there have been far better answers than my admittedly rudimentary and pretty bad answer (I was young, don't kill me).

    The other solutions in this thread are safer and better solutions. Preferably, I'd go with either of these two:

    • Charle's Duffy's solution
    • Håkon Hægland's solution

    Original answer for historic purposes (but please don't use this)

    If I'm not mistaken, "~" will not be expanded by a bash script in that manner because it is treated as a literal string "~". You can force expansion via eval like this.

    #!/bin/bash
    
    homedir=~
    eval homedir=$homedir
    echo $homedir # prints home path
    

    Alternatively, just use ${HOME} if you want the user's home directory.

提交回复
热议问题