击扩大变量的变量 [英] Bash expand variable in a variable

查看:128
本文介绍了击扩大变量的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立我的 PS1 提示符变量动态地选择一种颜色。要做到这一点,我已经定义了一堆局部变量的颜色名称:

I'm trying to set up my PS1 prompt variable to dynamically choose a color. To do this, I've defined a bunch of local variables with color names:

$ echo $Green
\033[0;32m

但我希望使用那些在动态分配变量,但我想不出如何正确展开:

but I was hoping to use those in dynamically assigning variables, but I can't figure out how to expand them properly:

> colorstr="\${$color}"
> echo $colorstr
${Green}

我试过的评估回声,和双引号,并没有显得十几组合工作。逻辑方式(我认为),以扩大其在错误变量的结果:

I've tried a dozen combinations of eval, echo, and double-quotes, and none seem to work. The logical way (I thought) to expand the variable results in an error:

> colorstr="${$color}"
-bash: ${$color}: bad substitution

(为清楚起见,我使用了> 而不是 $ 的提示字符,但我使用庆典)

(for clarity I've used > instead of $ for the prompt character, but I am using bash)

我怎样才能展开变量?即,以某种方式得到了这个词的绿色的值 \\ 033 [0;32米?和prefereably,有bash或终端解析 \\ 033 [0; 32立方米作为颜色太绿

How can I expand that variable? i.e., somehow get the word "Green" to the value \033[0;32m? And prefereably, have bash or the terminal parse that \033[0;32m as the color green too.

编辑:{!X}我是错用 $ EVAL回声$ X previously ,所以我接受了这些作为解决方案。对于(可能是病态)好奇,功能和 PS1 变量都在这个要点是: HTTPS ://gist.github.com/4383597

I was mis-using ${!x} and eval echo $x previously, so I've accepted those as solutions. For the (perhaps morbidly) curious, the functions and PS1 variable are on this gist: https://gist.github.com/4383597

推荐答案

使用评估是经典的解决方案,但庆典有一个更好的(更容易控制,少铳般的)解决方案:

Using eval is the classic solution, but bash has a better (more easily controlled, less blunderbuss-like) solution:


  • $ {!颜色}

  • ${!colour}

Bash的(4.1)参考手册说:

The Bash (4.1) reference manual says:

如果参数的第一个字符是一个感叹号(!),可变间接级别
  介绍。 Bash使用从参数的其余部分形成的变量的值
  变量的名称;然后这个变量被扩展并且该值在其余部分中使用
  的取代,而不是参数本身的值。这被称为间接
  扩展

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

例如:

$ Green=$'\033[32;m'
$ echo "$Green" | odx
0x0000: 1B 5B 33 32 3B 6D 0A                              .[32;m.
0x0007:
$ colour=Green
$ echo $colour
Green
$ echo ${!colour} | odx
0x0000: 1B 5B 33 32 3B 6D 0A                              .[32;m.
0x0007:
$

(即 ODX 命令极不规范,而只是转储与右图所示打印字符的十六进制格式的数据。由于平原回声并没有表现出任何东西,我需要看看正在回荡,我用了一个老朋友,我大约24年前写的。)

(The odx command is very non-standard but simply dumps its data in a hex format with printable characters shown on the right. Since the plain echo didn't show anything and I needed to see what was being echoed, I used an old friend I wrote about 24 years ago.)

这篇关于击扩大变量的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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