简体   繁体   English

bash:扩展变量

[英]bash: expanding variable

I'm trying to add a function to my .bashrc to ease prepending $PWD to environment variables. 我正在尝试向我的.bashrc添加一个函数,以简化将$PWD附加到环境变量的操作。 I'd like the function to take one argument -- the name of the variable on which to prepend the working directory. 我希望该函数采用一个参数-在工作目录之前添加变量的名称。 I'm thinking something like this... 我在想这样的事情...

function prependTo{ export $1=$PWD:\$$1 }

Is what I'm looking to do possible in bash? 我想用bash做些什么吗?

Don't use the function keyword, it is deprecated and non-POSIX. 不要使用function关键字,因为它已被弃用,并且不是POSIX。 Instead do this: 而是这样做:

 prependTo(){ export $1=$PWD:${!1}; }

Explanation 说明

From man bash man 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; Bash使用由其余参数形成的变量的值作为变量的名称; 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. 这称为间接扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM