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

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

    If the variable var is input by the user, eval should not be used to expand the tilde using

    eval var=$var  # Do not use this!
    

    The reason is: the user could by accident (or by purpose) type for example var="$(rm -rf $HOME/)" with possible disastrous consequences.

    A better (and safer) way is to use Bash parameter expansion:

    var="${var/#\~/$HOME}"
    

提交回复
热议问题