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

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

    Simplest: replace 'magic' with 'eval echo'.

    $ eval echo "~"
    /whatever/the/f/the/home/directory/is
    

    Problem: You're going to run into issues with other variables because eval is evil. For instance:

    $ # home is /Users/Hacker$(s)
    $ s="echo SCARY COMMAND"
    $ eval echo $(eval echo "~")
    /Users/HackerSCARY COMMAND
    

    Note that the issue of the injection doesn't happen on the first expansion. So if you were to simply replace magic with eval echo, you should be okay. But if you do echo $(eval echo ~), that would be susceptible to injection.

    Similarly, if you do eval echo ~ instead of eval echo "~", that would count as twice expanded and therefore injection would be possible right away.

提交回复
热议问题