获取变量作为输入的名称,该名称更改变量 [英] Get name of a variable as input and change the variable with that name
问题描述
我从剧本用户作为第一个参数变量的名字,我呼应上述变量值回控制台:
I get the name of a variable from the script user as the first argument and I echo the value of said variable back to the console:
#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}
这个伟大的工程!
我不能去工作,如果我想这个变量转变为从用户的第二个参数的值。有语法错误的一个例子是:
What I can't get to work is if I want to change that variable into the value of the second argument from the user. An example with a syntax error is:
#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}
echo "I will now try to change the value into $2."
(!variablename}=$2
# The above line generates: {!variablename}=2: command not found
在换句话说:如果有可能,我怎么从用户和两个读(已经解决)一个变量的名称的和写入所述可变
In other words: If it is possible, how do I get a variable name from the user and both read (already solved) and write to said variable?
推荐答案
我有一个闪光灯忽然,分寻求帮助后,我想我有一个解决办法:
I had a flash all of a sudden, minutes after asking for help, and I think I have a solution:
#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}
echo "I will now try to change the value into $2."
eval "$variablename=$2"
echo "Success! $variablename now has the value ${!variablename}!"
它的工作原理。有没有更好的办法?
It works. Is there a better way?
这篇关于获取变量作为输入的名称,该名称更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!