如何在 bash 中手动扩展特殊变量(例如:~波浪号) [英] How to manually expand a special variable (ex: ~ tilde) in bash
问题描述
我的 bash 脚本中有一个变量,它的值是这样的:
I have a variable in my bash script whose value is something like this:
~/a/b/c
请注意,它是未展开的波浪号.当我对这个变量执行 ls -lt 时(称之为 $VAR),我没有得到这样的目录.我想让 bash 解释/扩展这个变量而不执行它.换句话说,我希望 bash 运行 eval 但不运行评估的命令.这在 bash 中可能吗?
Note that it is unexpanded tilde. When I do ls -lt on this variable (call it $VAR), I get no such directory. I want to let bash interpret/expand this variable without executing it. In other words, I want bash to run eval but not run the evaluated command. Is this possible in bash?
我是如何在不扩展的情况下将其传递到我的脚本中的?我用双引号将它括起来传递了参数.
How did I manage to pass this into my script without expansion? I passed the argument in surrounding it with double quotes.
试试这个命令看看我的意思:
Try this command to see what I mean:
ls -lt "~"
这正是我所处的情况.我想要扩展波浪号.换句话说,我应该用什么来替换魔法以使这两个命令相同:
This is exactly the situation I am in. I want the tilde to be expanded. In other words, what should I replace magic with to make these two commands identical:
ls -lt ~/abc/def/ghi
和
ls -lt $(magic "~/abc/def/ghi")
注意 ~/abc/def/ghi 可能存在也可能不存在.
Note that ~/abc/def/ghi may or may not exist.
推荐答案
由于 StackOverflow 的性质,我不能让这个答案不被接受,但是在我发布这个问题的 5 年间,已经有比我公认的简陋和糟糕的答案要好得多(我还年轻,不要杀了我).
该线程中的其他解决方案是更安全、更好的解决方案.最好,我会选择这两个中的任何一个:
The other solutions in this thread are safer and better solutions. Preferably, I'd go with either of these two:
出于历史目的的原始答案(但请不要使用这个)
如果我没记错的话,"~"
不会被 bash 脚本以这种方式扩展,因为它被视为文字字符串 "~"
.您可以像这样通过 eval
强制扩展.
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
或者,如果您想要用户的主目录,只需使用 ${HOME}
.
Alternatively, just use ${HOME}
if you want the user's home directory.
这篇关于如何在 bash 中手动扩展特殊变量(例如:~波浪号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!