如何手动扩展一个特殊的变量:在bash(前〜波浪号) [英] How to manually expand a special variable (ex: ~ tilde) in bash

查看:164
本文介绍了如何手动扩展一个特殊的变量:在bash(前〜波浪号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量在我的bash脚本,它的值是这样的:

I have a variable in my bash script whose value is something like this:

~/a/b/c

请注意,这是未展开的波浪。当我做LS -lt此变量(称之为$ VAR),我得到没有这样的目录。我想让庆典间preT /扩展这个变量不执行它。换句话说,我要的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.

推荐答案

由于计算器的性质,我不能只让这个答案不被接受,但在中间5年因为我张贴了这个已经有比我固然简陋和pretty不好回答更好的答案(我年轻的时候,不要杀我)。

在此线程的其他解决方案更安全,更好的解决方案。 preferably,我会去与这两种的:

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

原来的答复为历史性的目的(但请不要用这个)

如果我没有记错,将不会以这种方式一个bash脚本,因为它是为文字字符串处理扩展。您可以强制通过评估扩张是这样的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆