gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:30:39 25 4
gpt4 key购买 nike

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

应该显示20

我主要是想生成变量名 OUTPUT_IN

如何解决?

最佳答案

您可以像这样在 Bash 中使用间接寻址:

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

但是,您可能应该使用数组或其他一些方法来执行您想要的操作。来自 BashFAQ/006 :

Putting variable names or any other bash syntax inside parameters is generally a bad idea. 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.

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

并且您应该尽可能避免使用 eval。来自 BashFAQ/048 :

If the variable contains a shell command, the shell might run that command, whether you wanted it to or not. This can lead to unexpected results, especially when variables can be read from untrusted sources (like users or user-created files).

Bash 4 有关联数组,可以让你这样做:

array[in]=10
array[out]=20
index="out"
echo "${array[$index]}"

关于linux - 如何在 shell 脚本中加入 2 个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com