简体   繁体   English

如何在shell脚本中加入2变量?

[英]How join 2 variable in shell script?

INPUT=10     
OUTPUT_IN=20     
KEYWORD="IN"    
echo $OUTPUT_"$KEYWORD"   

It should display 20 它应该显示20

Mainly I am looking to generate the variable name OUTPUT_IN 我主要是想生成变量名OUTPUT_IN

How to resolve this? 怎么解决这个?

You can use indirection in Bash like this: 您可以像这样在Bash中使用间接:

INPUT=10     
OUTPUT_IN=20     
KEYWORD="IN"    
var="OUTPUT_$KEYWORD"
echo "${!var}"

However, you should probably use an array or some other method to do what you want. 但是,您可能应该使用数组或其他方法来执行所需的操作。 From BashFAQ/006 : BashFAQ / 006

Putting variable names or any other bash syntax inside parameters is generally a bad idea. 将变量名称或任何其他bash语法放在参数中通常是一个坏主意。 It violates the separation between code and data; 它违反了代码和数据之间的分隔; and as such brings you on a slippery slope toward bugs, security issues etc. Even when you know you "got it right", because you "know and understand exactly what you're doing", bugs happen to all of us and it pays to respect separation practices to minimize the extent of damage they can have. 这样一来,您就容易遇到bug,安全问题等。即使您知道自己“做对了”,因为“知道并确切地了解自己在做什么”,bug还是会发生在我们所有人身上,这是值得的尊重分离做法,以最大程度地减少其可能造成的损害。

Aside from that, it also makes your code non-obvious and non-transparent. 除此之外,它还使您的代码不明显且不透明。

Normally, in bash scripting, you won't need indirect references at all. 通常,在bash脚本中,您根本不需要间接引用。 Generally, people look at this for a solution when they don't understand or know about Bash Arrays or haven't fully considered other Bash features such as functions. 通常,人们在不了解或不了解Bash数组或未完全考虑其他Bash功能(例如功能)的情况下,会将此视为一种解决方案。

And you should avoid using eval if at all possible. 而且,如果可能,应避免使用eval From BashFAQ/048 : 来自BashFAQ / 048

If the variable contains a shell command, the shell might run that command, whether you wanted it to or not. 如果变量包含shell命令,则无论您是否需要,shell都可以运行该命令。 This can lead to unexpected results, especially when variables can be read from untrusted sources (like users or user-created files). 这可能会导致意外结果,尤其是当可以从不受信任的源(例如用户或用户创建的文件)读取变量时。

Bash 4 has associative arrays which would allow you to do this: Bash 4具有关联数组,您可以执行以下操作:

array[in]=10
array[out]=20
index="out"
echo "${array[$index]}"
eval newvar=\$$varname

来源:《 高级Bash脚本指南》,间接参考

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

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