如何在bash中手动扩展一个特殊变量(例如:〜tilde)(How to manually expand a special variable (ex: ~ tilde) in bash)

系统教程 行业动态 更新时间:2024-06-14 17:03:54
如何在bash中手动扩展一个特殊变量(例如:〜tilde)(How to manually expand a special variable (ex: ~ tilde) in bash)

我的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/c

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

and

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 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.

更多推荐

本文发布于:2023-04-24 14:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/1678ed3eeee499903803b7187455ec67.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何在   bash   tilde   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!