我的bash脚本中有一个变量,其值是这样的:
~/a/b/c请注意,它是未膨胀的波浪号。 当我在这个变量上调用ls -lt(调用$ VAR)时,我没有这样的目录。 我想让bash解释/展开这个变量而不执行它。 换句话说,我想要bash运行eval,但不运行evaluate命令。 这是可能在bash吗?
我如何设法将其传递到我的脚本而不扩展? 我用双引号传递了围绕它的参数。
尝试这个命令来看看我的意思:
ls -lt "~"这正是我所处的情况。我想要将波浪号扩大。 换句话说,我应该用什么替代魔术来使这两个命令相同:
ls -lt ~/abc/def/ghi和
ls -lt $(magic "~/abc/def/ghi")注意〜/ abc / def / ghi可能存在或可能不存在。
I have a variable in my bash script whose value is something like this:
~/a/b/cNote 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/ghiand
ls -lt $(magic "~/abc/def/ghi")Note that ~/abc/def/ghi may or may not exist.
最满意答案
由于StackOverflow的性质,我不能只是让这个答案不被接受,但是在我发布这段时间后的5年里,已经有了比我绝对不可思议的和糟糕的答案好的答案(我很年轻,不要杀死我)。
该线程中的其他解决方案是更安全和更好的解决方案。 最好我会和这两个人一起去
Charle's Duffy的解决方案 HåkonHægland的解决方案原始答案为历史目的(但请不要使用)
如果我没有错, "~"不会被bash脚本以这种方式扩展,因为它被视为字符串"~" 。 你可以通过eval强制扩展。
#!/bin/bash homedir=~ eval homedir=$homedir echo $homedir # prints home path或者,如果您想要用户的主目录,只需使用${HOME} 。
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 solutionOriginal 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 pathAlternatively, just use ${HOME} if you want the user's home directory.
更多推荐
发布评论